-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheckBSTBalance.java
75 lines (60 loc) · 1.68 KB
/
CheckBSTBalance.java
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
import java.util.Stack;
/*
* Implement a function to check if a binary tree is balanced. A
* balanced tree is defined to be a tree such that the heights of
* the two subtrees of any node never differ by more than one.
*/
public class CheckBSTBalance {
public static class BSTNode {
// Data not necessary for this problem, so it was omitted
BSTNode left;
BSTNode right;
}
/*
* returns true if balanced, false if not
*/
public boolean checkTreeBalance(BSTNode root) {
Stack<BSTNode> current = new Stack<BSTNode>();
Stack<BSTNode> next = new Stack<BSTNode>();
int imbalance = -1;
boolean subTreeEnd = false;
current.push(root);
while(!current.isEmpty()) {
BSTNode c = current.pop();
if (c.left != null)
next.push(c.left);
if (c.right != null)
next.push(c.right);
if (c.left == null || c.right == null)
subTreeEnd = true;
if (current.isEmpty()) {
if (subTreeEnd)
imbalance++;
if (imbalance > 1)
return false;
Stack<BSTNode> temp = current;
current = next;
next = temp;
}
}
return true;
}
public static void main(String[] args) {
CheckBSTBalance test = new CheckBSTBalance();
BSTNode tree = new BSTNode();
tree.left = new BSTNode();
tree.right = new BSTNode();
//true
System.out.println(test.checkTreeBalance(tree));
//true
tree.right.right = new BSTNode();
System.out.println(test.checkTreeBalance(tree));
//false
tree.right.right.right = new BSTNode();
System.out.println(test.checkTreeBalance(tree));
//false
tree.right.right.right = new BSTNode();
tree.right.right.right.left = new BSTNode();
System.out.println(test.checkTreeBalance(tree));
}
}