2014年10月5日星期日

[Leetcode] 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.
判断每一个节点的两棵子树的深度(最大)不能超过1,并且两棵子树都是Balanced的话,那么这个节点也是合法的。
    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);
    }
    
    private int depth(TreeNode root) {
        if(root == null) return 0;
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }

没有评论:

发表评论