110. Balanced Binary Tree
given бинарное cây, определите, является ли оно
сбалансированным по высоте.
Ví dụ:
Input: root = [3,9,20,null,null,15,7]
Output: true
C# lời giải
đã khớp/gốcpublic class Solution {
private int Height(TreeNode root) {
if (root == null) {
return -1;
}
return 1 + Math.Max(Height(root.left), Height(root.right));
}
public bool IsBalanced(TreeNode root) {
if (root == null) {
return true;
}
return Math.Abs(Height(root.left) - Height(root.right)) < 2 &&
IsBalanced(root.left) && IsBalanced(root.right);
}
}
C++ lời giải
bản nháp tự động, xem lại trước khi gửi#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
private int Height(TreeNode root) {
if (root == null) {
return -1;
}
return 1 + max(Height(root.left), Height(root.right));
}
public bool IsBalanced(TreeNode root) {
if (root == null) {
return true;
}
return abs(Height(root.left) - Height(root.right)) < 2 &&
IsBalanced(root.left) && IsBalanced(root.right);
}
}
Java lời giải
đã khớp/gốcclass Solution {
private int height(TreeNode root) {
if (root == null) {
return -1;
}
return 1 + Math.max(height(root.left), height(root.right));
}
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return (
Math.abs(height(root.left) - height(root.right)) < 2 &&
isBalanced(root.left) &&
isBalanced(root.right)
);
}
}
JavaScript lời giải
đã khớp/gốcvar height = function (root) {
if (root == null) {
return -1;
}
return 1 + Math.max(height(root.left), height(root.right));
};
var isBalanced = function (root) {
if (root == null) {
return true;
}
return (
Math.abs(height(root.left) - height(root.right)) < 2 &&
isBalanced(root.left) &&
isBalanced(root.right)
);
};
Python lời giải
đã khớp/gốcclass Solution:
def height(self, root: TreeNode) -> int:
if not root:
return -1
return 1 + max(self.height(root.left), self.height(root.right))
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
return (
abs(self.height(root.left) - self.height(root.right)) < 2
and self.isBalanced(root.left)
and self.isBalanced(root.right)
)
Go lời giải
đã khớp/gốcfunc height(root *TreeNode) int {
if root == nil {
return -1
}
return 1 + max(height(root.Left), height(root.Right))
}
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
return abs(height(root.Left)-height(root.Right)) < 2 &&
isBalanced(root.Left) &&
isBalanced(root.Right)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
Algorithm
1️⃣
Сначала мы определяем функцию height, которая для любого узла p в дереве T returns:
-1, если p является пустым подcâyм, т.е. null;
1 + max(height(p.left), height(p.right)) в противном случае.
2️⃣
Теперь, когда у нас есть метод для определения высоты дерева, остается только сравнить высоты детей каждого узла. cây T с корнем r является сбалансированным тогда и только тогда, когда высоты его двух детей отличаются не более чем на 1 и поддеревья каждого ребенка также сбалансированы.
3️⃣
Следовательно, мы можем сравнить высоты двух дочерних поддеревьев, а затем рекурсивно проверить каждое из них:
Если root == NULL, возвращаем true.
Если abs(height(root.left) - height(root.right)) > 1, возвращаем false.
В противном случае возвращаем isBalanced(root.left) && isBalanced(root.right).
😎
Vacancies for this task
việc làm đang hoạt động with overlapping task tags are đã hiển thị.