题目
Given a binary tree, determine if it is height-balanced.
答案
这个答案用了一个小技巧
recursion返回值大于0时是在计算树的高度
recursion返回值小于0时,证明发现了2个高度差大于1的subtrees
class Solution {
public boolean isBalanced(TreeNode root) {
return recur(root) != -1;
}
private int recur(TreeNode r) {
if(r == null) return 0;
int hl = recur(r.left);
int hr = recur(r.right);
if(hl == -1 || hr == -1) return -1;
if(Math.abs(hr - hl) > 1) return -1;
return Math.max(hl, hr) + 1;
}
}