码迷,mamicode.com
首页 > 其他好文 > 详细

Balanced Binary Tree

时间:2014-10-12 07:47:07      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

/**
 * 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

标签:style   blog   color   io   ar   for   sp   div   on   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!