您的位置:首页 > 其它

leetcode - 110. Balanced Binary Tree

2018-01-29 22:16 183 查看
Problem:

 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.

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,

例如Example 2中结点1左子树深度为3,右子树深度为1,相差超过1,就不是平衡二叉树了。

Solve:

就是求结点深度再判断的思想,调用递归解决,

①。求左结点深度,

②。求右结点深度,

③。左右比较,绝对值大于1的话返回-1;(结点深度不会是-1,所以-1是对非平衡的标识)

(时间复杂度O(n)AC-1ms
public boolean isBalanced(TreeNode root) {
if(getMaxDepth(root)==-1){
return false;
}
return true;
}
public static int getMaxDepth(TreeNode root) {
if (root == null){
return 0;
} else {
int left = getMaxDepth(root.left);//左结点深度
int right = getMaxDepth(root.right);//右结点深度
if(left==-1||right==-1) return -1;
if(left-right>1||right-left>1){//非平衡返回-1
return -1;
}
return 1 + Math.max(left, right);//求最大深度
}
}


后记:这道题开始想着是求根结点最大深度 然后求最小深度,两个绝对值大于1判断为非平衡树的,后来发现概念错了,

是对每个结点而言的,其实弄清概念很重要,再者代码根据求解树深度算法进行改造,理解了的话也不是很难。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: