Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Solution:递归post-order dfs来upwards累积height
思路: 利用递归post-order dfs来upwards累积height,并在过程中判断是否Math.abs(left_height - right_height) > 1 for early stop
Note:
Time Complexity: O(N) Space Complexity: O(N) 递归缓存
Solution Code:
class Solution {
public boolean isBalanced(TreeNode root) {
return dfsHeight(root) != -1;
}
private int dfsHeight(TreeNode root) {
// post-order dfsly check from left-bottom and accumulate max_height upwards
// meanwhile, check if |left_height - right_height)| > 1 for early stop
if(root == null) return 0;
int left_height = dfsHeight(root.left);
if(left_height == -1) return -1;
int right_height = dfsHeight(root.right);
if(right_height == -1) return -1;
if(Math.abs(left_height - right_height) > 1) return -1;
return Math.max(left_height, right_height) + 1;
}
}
Solution2:
Solution2是O(NlogN)的方法,避免使用,因为每个结点都要去求depth(重复计算)
不是O(N^2)因为是balanced,否则就return。
time complexity for depth:T(n) = 2T(n/2) + O(1) => O(N) ,
只对当前点看,每个当前点一下都当成N,因为是一次depth总。要遍历每个结点的depth是在下面考虑的,有n/2二分。
Time complexity for isBalanced: T(n) = 2T(n/2) + O(n) => O(NlogN)
O(n)是求depth的;n/2是因为是balanced的否则return
class Solution2 {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int left_height = getMaxDepth(root.left);
int right_height = getMaxDepth(root.right);
return Math.abs(left_height - right_height) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int getMaxDepth(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(getMaxDepth(root.left), getMaxDepth(root.right));
}
}