首页 > 其他 > 详细

Balanced Binary Tree

时间:2014-10-12 06:04:58      阅读:249      评论:0      收藏:0      [点我收藏+]
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null)
            return true;
        int l = height(root.left);
        int r = height(root.right);
        if(Math.abs(l-r)>1)
            return false;
        return isBalanced(root.left) && isBalanced(root.right);
    }
    
    public int height(TreeNode root){
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        int l = height(root.left);
        int r = height(root.right);
        return Math.max(l,r) + 1;
    }
}

 

 

于是我想到了 bottom-up 也就是后序遍历

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    boolean check = true;
    public boolean isBalanced(TreeNode root) {
        if(root==null)
            return true;
        int l = height(root.left);
        int r = height(root.right);
        if(Math.abs(l-r)>1)
            return false;
        return check;
    }
    
    public int height(TreeNode root){
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        int l = height(root.left);
        int r = height(root.right);
        if(Math.abs(l-r)>1)
          check = false;
        return Math.max(l,r) + 1;
    }
}

苦于让height() return height  如果不必配就return false.    下面有一个非常聪明的方法。

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    boolean check = true;
    public boolean isBalanced(TreeNode root) {
        if(root==null)
            return true;
        if(getHeight(root)== -1)
            return false;
        return true;
    }
    
    public int getHeight(TreeNode root){
        if(root == null)
            return 0;
       
        int l = getHeight(root.left);
        int r = getHeight(root.right);
        if(l == -1 || r == -1)
            return -1;
        if(Math.abs(l-r)>1)
          return -1;
        return Math.max(l,r) + 1;
    }
}

 

Balanced Binary Tree

原文:http://www.cnblogs.com/leetcode/p/4020092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!