Given a binary tree, determine if it is height-balanced.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:
Input: root = []
Output: true
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
// Height Function will return -1, when it’s an unbalanced tree...
if (Height(root) == -1) return false;
return true;
}
public int Height(TreeNode root) {
if (root == null) return 0;
int leftHeight = Height(root.left);
int rightHight = Height(root.right);
// In case of left subtree or right subtree unbalanced, return -1...
if (leftHeight == -1 || rightHight == -1) return -1;
// If their heights differ by more than ‘1’, return -1...
if (Math.abs(leftHeight - rightHight) > 1) return -1;
// Otherwise, return the height of this subtree as max(leftHeight, rightHight) + 1...
return Math.max(leftHeight, rightHight) + 1;
}
}
Time:O(N) Space:O(H)
public int height(TreeNode node) {
// 如果節點為空,返回高度 0
if (node == null) {
return 0;
}
// 遞歸計算左子樹的高度
int leftHeight = height(node.left);
// 遞歸計算右子樹的高度
int rightHeight = height(node.right);
// 返回左子樹和右子樹中較大的高度加 1
return Math.max(leftHeight, rightHeight) + 1;
}