5/30/2014

21. Balanced Binary Tree

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

1 条评论:

  1. 1. 用到了2个recursive.
    2. for each node, if the maxDepth of its two subtrees differ by more than 1, return false.
    3. 先判断当前root满不满足,如果不满足return false,如果满足再去判断它的左右child.

    回复删除