- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem110.java
More file actions
Latest commit
42 lines (34 loc) · 1.12 KB
/
Copy pathProblem110.java
File metadata and controls
42 lines (34 loc) · 1.12 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
classProblem110 {
publicstaticvoidmain(String[] args) {
Problem110p = newProblem110();
TreeNoderoot = newTreeNode(1);
root.left = newTreeNode(2);
root.left.left = newTreeNode(3);
root.left.left.left = newTreeNode(4);
root.left.left.left.left = newTreeNode(5);
System.out.println(p.isBalanced(root));
}
publicbooleanisBalanced(TreeNoderoot) {
if (root == null) returntrue;
intrightHeight = height(root.right);
intleftHeight = height(root.left);
if (rightHeight <0 || leftHeight <0) {
returnfalse;
}
if (Math.abs(leftHeight - rightHeight) <= 1) {
returntrue;
}
returnfalse;
}
intheight(TreeNoderoot) {
if (root == null) return0;
intleftHeight = height(root.left);
intrightHeight = height(root.right);
interr = Math.abs(leftHeight - rightHeight);
if ( err > 1 || err < 0) {
returnInteger.MIN_VALUE;
}
intval = Math.max(leftHeight, rightHeight) + 1;
returnval;
}
}