您的位置:首页 > 其它

leetcode -- 110. Balanced Binary Tree 【二叉树是否平衡】

2017-02-09 13:04 555 查看
题目

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.

题意

给定一个二叉树,判断其是否是高度-平衡的。

对于这个问题,高度平衡的意思是,一个二叉树,其中每个节点的左右子树的高度差不大于1.

分析及解答

平衡因子

某结点的左子树与右子树的高度(深度)差即为该结点的平衡因子(BF,Balance Factor)。
平衡二叉树上所有结点的平衡因子只可能是 -1,0 或 1。

特殊之处:不平衡标识 + 高度计算】在下面这个算法中有个比较特殊的地方,他是将判断因素加入到高度计算中了。(在高度中 ,以 取出 -1 作为不平衡的标识,出现差的绝对值大于1的时候,则归纳到-1.)
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
return height(root)!=-1;

}
public int height(TreeNode node){
if(node==null){
return 0;
}
int lH=height(node.left);
if(lH==-1){
return -1;
}
int rH=height(node.right);
if(rH==-1){
return -1;
}
if(lH-rH<-1 || lH-rH>1){
return -1;
}
return Math.max(lH,rH)+1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode-easy 二叉树