forked from mengli/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedBinaryTree.java
More file actions
Latest commit
28 lines (25 loc) · 698 Bytes
/
Copy pathBalancedBinaryTree.java
File metadata and controls
28 lines (25 loc) · 698 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Given a binary tree, determine if it is height-balanced.
*
* For this problem, a height-balanced binary tree is defined as a binary tree
* in which the depth of the two subtrees of every node never differ by more
* than 1.
*
*/
publicclassBalancedBinaryTree {
publicbooleanisBalanced(TreeNoderoot) {
returndetermine(root) >= 0 ? true : false;
}
privateintdetermine(TreeNoderoot) {
if (root == null) {
return0;
} else {
intleftDepth = determine(root.left);
intrightDepth = determine(root.right);
if (leftDepth < 0 || rightDepth < 0
|| Math.abs(leftDepth - rightDepth) > 1)
return -1;
returnMath.max(leftDepth, rightDepth) + 1;
}
}
}