110. Balanced Binary Tree
正常DFS是check一个点的左右深度,比较,满足的话再check左右节点,这样的话有很多重复运算。
bottom-up就比较合理,一旦发现不满足的,可以不再CHECK,直接返还FALSE就行了。
和那个找least common ancestor的有点像
public class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
public int getHeight(TreeNode root) {
if (root == null) return 0;
int left = getHeight(root.left);
if (left == -1) return -1;
int right = getHeight(root.right);
if (right == -1) return -1;
if(Math.abs(left - right) > 1) return -1;
else return Math.max(left, right) + 1;
}
}
回头看很多E难度的题不是做完了就那么简单的,也值得总结,我这三刷才开始总结E难度的。。

浙公网安备 33010602011771号