BiruLyu
5/25/2017 - 5:53 PM

110. Balanced Binary Tree.java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        return helper(root) != -1;
    }
    
    public int helper(TreeNode root){
        if(root == null) return 0;
        //if(helper(root.left) == -1 || helper(root.right) == -1) return -1;
        int leftHeight = helper(root.left);//存一下这个数,否则超时
        if(leftHeight == -1) return -1;
        int rightHeight = helper(root.right);
        if(rightHeight == -1) return -1;
        if(Math.abs(leftHeight - rightHeight)  > 1) return -1;
        return Math.max(leftHeight, rightHeight) + 1;
    }
}

/*
[]
[1,2,3,4,5,6,null,7]
[1,2,3,4,5,6,null,7,8,9,10]
[1,2,3,4,5,6,null,7,8,9,10,null,null,11,12,13,14,15,16,17,18]
[1,2,3,4,null,5,null,6]
*/