[LeetCode] Balanced Binary Tree 平衡二叉树
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 everynode never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
求二叉树是否平衡,根据题目中的定义,高度平衡二叉树是每一个结点的两个子树的深度差不能超过1,那么我们肯定需要一个求各个点深度的函数,然后对每个节点的两个子树来比较深度差,时间复杂度为O(NlgN),代码如下:
其实就是前一道计算各个节点高度的题目 我们增加一个比较环节
class Solution {
boolean result = true;
public boolean isBalanced(TreeNode root) {
height(root);
return result;
}
private int height(TreeNode root){
if(root == null)
return 0;
if(root.left == null && root.right == null)
return 1;
int left = height(root.left);
int right = height(root.right);
if(Math.abs(left - right) > 1)
result = false;
return Math.max(left, right) + 1;
}
}