Monday, November 2, 2015

[leetcode] Balanced Binary Tree

要注意left-right 要用绝对值


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (heightOfTree(root) == -1){
            return false;
        }
        return true;
    }
    
    private int heightOfTree(TreeNode root){
        if (root == null){
            return 0;
        }
        int left = heightOfTree(root.left);
        int right = heightOfTree(root.right);
        if (left == -1 || right == -1 || Math.abs(left-right) > 1){
            return -1;
        }
        return Math.max(left, right)+1;
    }
}

No comments:

Post a Comment