2014年1月16日星期四

LeetCoder - 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.

/**
 * 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;
        }
        return Math.abs(depth(root.left)-depth(root.right))<=1 && isBalanced(root.left) && isBalanced(root.right);
    }
 
    public int depth(TreeNode root) {
        if(root==null) {
            return 0;
        } else {
            return 1 + Math.max(depth(root.left), depth(root.right));
        }
    }
}


/**
 * 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;
        }
        return getDepth(root, 0)!=-1;
    }
   
    private int getDepth(TreeNode node, int curDepth) {
        if(node==null) {
            return curDepth;
        }
        int leftDep = curDepth;
        int rightDep = curDepth;
        if(node.left!=null) {
            leftDep = getDepth(node.left, leftDep + 1);
        }
        if(leftDep==-1) {
            return -1;
        }
        if(node.right!=null) {
            rightDep = getDepth(node.right, rightDep + 1);
        }
        if(rightDep==-1) {
            return -1;
        }
        int gap = (int) Math.abs(rightDep-leftDep);
        if(gap>1) return -1;
        else return Math.max(leftDep, rightDep);
    }
}

没有评论:

发表评论