[LintCode/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.

Example

Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7

The binary tree A is a height-balanced binary tree, but B is not.

Note

根据二叉平衡树的定义,我们先写一个求二叉树最大深度的函数depth()。在主函数中,利用比较左右子树depth的差值来判断当前结点的平衡性,如果不满足则返回false。然后递归当前结点的左右子树,得到结果。

Solution

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        if (Math.abs(depth(root.left)-depth(root.right)) > 1) return false;
        return isBalanced(root.left) && isBalanced(root.right);
    }
    public int depth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(depth(root.left), depth(root.right))+1;
    }
}

你可能感兴趣的:(java,divide-conquer,recursion)