LeetCode: Balanced Binary Tree

LeetCode: Balanced Binary Tree

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