Sunday, April 5, 2015

Balanced Binary Tree

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.
Solution: recursion
用一个整数来做返回值,0或者正数表示树的深度,-1表示此树已经不平衡了。
如果已经不平衡,则递归一直返回-1即可。
否则就利用返回的深度信息看看左右子树是不是违反平衡条件,如果违反返回-1。
否则返回左右子树深度大的加一作为自己的深度即可。
Run time complexity is O(n), space complexity is stack space O(logn).
/**
 * 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) {
        return helper(root) >= 0;
    }
    
    public int helper(TreeNode root) {
        if(root == null)
            return 0;
            
        int left = helper(root.left);
        int right = helper(root.right);
        
        //如果不balance,会返回-1,所以只要left或者right小于0,就说明不balance了。
        //balance的话会返回深度,一定是一个正数。
        if(left < 0 || right < 0) {   
            return -1;
        }
        
        if(Math.abs(left - right) > 1) {
            return -1;
        }
        
        return Math.max(left, right) + 1;
    }
}
Reference:http://blog.csdn.net/linhuanmars/article/details/23731355
Or
/**
 * 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 depthL = getDepth(root.left);
        int depthR = getDepth(root.right);
        if(Math.abs(depthL - depthR) > 1) {
            return false;
        }else {
            boolean balancedL = isBalanced(root.left);
            boolean balancedR = isBalanced(root.right);
            return balancedL && balancedR;
        }
    }
    
    public int getDepth(TreeNode root) {
        if(root == null)
            return 0;
        return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
    }
}

No comments:

Post a Comment