您的位置:首页 > 其它

leedcode做题总结,题目Balanced Binary Tree 2012/10/08

2014-07-12 21:08 561 查看
检测平衡二叉树,应该算是很简单的题目了,递归每个节点先求出左右子树的高,如果相差小于2在判断子节点们是不都平衡

public int hig(TreeNode root){
if(root==null)return 0;
return Math.max(hig(root.left),hig(root.right))+1;
}

public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(Math.abs(hig(root.left)-hig(root.right))<2)
return isBalanced(root.left)&&isBalanced(root.right);
else return false;
}


Update 2015/08/17: 上面的答案不好,isBalanced()是从上往下递归,每一次都用调用hig在此从上往下递归,所以很多计算是重复的,这道题应该从下往上计算,一边计算高度一边判断,方法如下:

/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
public int check(TreeNode node){
if (node == null){
return 0;
}
int lheight = check(node.left);
int rheight = check(node.right);
if (lheight == -1 || rheight == -1){
return -1;
}
if (Math.abs(lheight - rheight) > 1){
return -1;
}
return Math.max(lheight, rheight) + 1;
}
public boolean isBalanced(TreeNode root) {
// write your code here
if (check(root) == -1)
return false;
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: