-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsBalance.java
More file actions
78 lines (49 loc) · 1.47 KB
/
IsBalance.java
File metadata and controls
78 lines (49 loc) · 1.47 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class IsBalanceTree{
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int v){
value = v;
left = null;
right = null;
}
}
public static Node randomTree(int currLevel,int maxLevel){
if(currLevel > maxLevel || Math.random() > 0.7)
return null;
Node head = new Node((int)(Math.random()*1000));
head.left = randomTree(currLevel+1,maxLevel);
head.right = randomTree(currLevel+1,maxLevel);
return head;
}
public static Node getRandomTree(int maxLevel){
return randomTree(1,maxLevel);
}
private static class IsBalanceInfo{
public boolean isBalance;
public int high;
public IsBalanceInfo(boolean balance,int h){
isBalance=balance;
high = h;
}
}
// public static IsBalanceInfo isBalanceTree(Node head){
// }
public static IsBalanceInfo isBalanceTreeProcess(Node head){
if(head == null){
return new IsBalanceInfo(true,0);
}
IsBalanceInfo leftInfo = isBalanceTreeProcess(head.left);
IsBalanceInfo rightInfo = isBalanceTreeProcess(head.right);
boolean isBalance = true;
if(!leftInfo.isBalance || !rightInfo.isBalance) isBalance=false;
if(Math.abs(leftInfo.high - rightInfo.high) >1) isBalance=false;
int high = Math.max(leftInfo.high , rightInfo.high) + 1;
return new IsBalanceInfo(isBalance,high);
}
public static void main(String[] args){
Node root = getRandomTree(5);
System.out.println("isBalance = "+isBalanceTreeProcess(root).isBalance);
}
}