-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathBinarySearchTreeIterator.java
80 lines (68 loc) · 1.91 KB
/
BinarySearchTreeIterator.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
76
77
78
79
80
/*
* Design an iterator over a binary search tree with the following rules:
Elements are visited in ascending order (i.e. an in-order traversal)
next() and hasNext() queries run in O(1) time in average.
Example
For the following binary search tree, in-order traversal by using iterator is
[1, 6, 10, 11, 12]
10
/ \
1 11
\ \
6 12
Challenge
Extra memory usage O(h), h is the height of the tree.
Super Star: Extra memory usage O(1)
*/
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* Example of iterate a tree:
* BSTIterator iterator = new BSTIterator(root);
* while (iterator.hasNext()) {
* TreeNode node = iterator.next();
* do something for node
* }
*/
public class BinarySearchTreeIterator {
}
class BSTIterator {
Stack<TreeNode> stack;
List<TreeNode> list;
TreeNode cur;
int index;
//@param root: The root of binary tree.
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
list = new LinkedList<TreeNode>();
cur = root;
index = 0;
iterator(cur, list);
}
public void iterator(TreeNode root, List<TreeNode> list) {
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode node = stack.pop();
cur = node.right;
list.add(node);
}
}
//@return: True if there has next node, or false
public boolean hasNext() {
return index < list.size();
}
//@return: return next node
public TreeNode next() {
return hasNext() ? list.get(index++) : null;
}
}