110.Balanced Binary Tree

Solution 1: accepted

Use -1 as flag of inbalanced tree. Use another variable for better practice in production.

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