-
Notifications
You must be signed in to change notification settings - Fork 111
/
binary-search-tree-iterator.cc
62 lines (54 loc) · 1.07 KB
/
binary-search-tree-iterator.cc
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
// Binary Search Tree Iterator
class BSTIterator {
public:
stack<TreeNode *> s;
BSTIterator(TreeNode *t) {
for (; t; t = t->left)
s.push(t);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return ! s.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *x = s.top();
s.pop();
int r = x->val;
for (x = x->right; x; x = x->left)
s.push(x);
return r;
}
};
// Morris inorder traversal
class BSTIterator {
public:
TreeNode *x;
BSTIterator(TreeNode *t) : x(t) {}
/** @return whether we have a next smallest number */
bool hasNext() {
return x != NULL;
}
/** @return the next smallest number */
int next() {
int r;
for(;;) {
TreeNode *y = x->left;
if (y) {
while (y->right && y->right != x)
y = y->right;
if (y->right)
y->right = NULL;
else {
y->right = x;
x = x->left;
continue;
}
}
r = x->val;
x = x->right;
break;
}
return r;
}
};