Tuesday, June 10, 2014

Balanced Binary Tree

给一个二叉树,判断是否是平衡树
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.
public class Solution {
    public boolean isBalanced(TreeNode root) {
        return checkHeight(root)==-1 ? false : true;
    }
    
    public int checkHeight(TreeNode root){
        if(root==null) return 0;
        int left = checkHeight(root.left);
        int right = checkHeight(root.right);
        //平衡树的条件,左右子树都是平衡树,且左右子树高度差不大于1
        if(left==-1 || right==-1 || Math.abs(left-right)>1)
            return -1;
        return Math.max(left, right)+1;
    }
}

No comments:

Post a Comment