2014年4月23日 星期三

[LeetCode] Balanced Binary Tree

Problem:
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:O(n)
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null)
            return true;
        else {
            int leftheight = getHeight(root.left);
            int rightheight = getHeight(root.right);
            if(leftheight<0 || rightheight<0)
                return false;
            if(leftheight == rightheight || leftheight-rightheight == 1 || leftheight-rightheight == -1) 
                return true;
                
            return false;    
        }    
    }
    
    public int getHeight(TreeNode root){
        if(root == null)
            return 0;
        int leftheight = getHeight(root.left);
        int rightheight = getHeight(root.right);
        if(leftheight<0 || rightheight<0 || (leftheight-rightheight)>1 || (rightheight-leftheight)>1)
            return -1;
        return Math.max(leftheight,rightheight)+1;
    }
}

沒有留言:

張貼留言