题目
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
解题思路
1.使用两个递归去逐个子树检查平衡
思路:
- 先用一个递归去遍历全部的节点,并检测这个子树的左右的最大深度差是否大于1
- 第二个递归去检测最大深度并返回。
- 【注意】root==null的时候返回true…
代码:
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true; // 注意,不然只要到叶节点那么就是null
} else {
return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}
public int height(TreeNode root) {
if (root == null) {
return 0;
} else {
return Math.max(height(root.left), height(root.right)) + 1;
}
}
}
性能: