力扣 LeetCode 110. 平衡二叉树(Day8:二叉树)
解题思路:
等于 -1 时,直接 return -1
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
public int getHeight(TreeNode root) {
if (root == null) return 0;
int leftDepth = getHeight(root.left);
if (leftDepth == -1) return -1;
int rightDepth = getHeight(root.right);
if (rightDepth == -1) return -1;
int res;
if (Math.abs(leftDepth - rightDepth) > 1) res = -1;
else res = 1 + Math.max(leftDepth, rightDepth);
return res;
}
}