-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP9_1.java
More file actions
49 lines (42 loc) · 1.07 KB
/
P9_1.java
File metadata and controls
49 lines (42 loc) · 1.07 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
43
44
45
46
47
48
49
class BalObj {
boolean balanced;
int height;
public BalObj(boolean balanced, int height)
{
this.balanced = balanced;
this.height = height;
}
}
public class P9_1 {
public static void main(String[] args) {
}
public boolean isBalanced(TreeNode root) {
BalObj leftBalanced = balanceCheck(root.left);
if(!leftBalanced.balanced) { return false;}
BalObj rightBalanced = balanceCheck(root.right);
if(!rightBalanced.balanced) { return false;}
return Math.abs(leftBalanced.height - rightBalanced.height) <= 1;
}
public static BalObj balanceCheck(TreeNode node)
{
if(node == null)
{
return new BalObj(true, 0);
}
BalObj leftBalanced = balanceCheck(node.left);
if(!leftBalanced.balanced)
{
return leftBalanced;
}
BalObj rightBalanced = balanceCheck(node.right);
if(!rightBalanced.balanced)
{
return rightBalanced;
}
if(Math.abs(leftBalanced.height - rightBalanced.height) > 1)
{
return new BalObj(false,0);
}
return new BalObj(true, Math.max(leftBalanced.height, rightBalanced.height) + 1);
}
}