-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathBinary_Search_Tree_Iterator.cpp
74 lines (64 loc) · 1.64 KB
/
Binary_Search_Tree_Iterator.cpp
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
stack<TreeNode*> nodeStack;
void pushAllLefts(TreeNode* node) {
while(node) {
nodeStack.push(node);
node = node->left;
}
}
public:
BSTIterator(TreeNode *root) {
pushAllLefts(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !nodeStack.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* current = nodeStack.top();
nodeStack.pop();
pushAllLefts(current->right);
return current->val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
// more than O(h) extra space
// O(n) space
class BSTIterator {
vector<int> nodes;
vector<int>::iterator iter;
void BSTIteratorUtils(TreeNode *node) {
if(!node) return;
BSTIteratorUtils(node->left);
nodes.push_back(node->val);
BSTIteratorUtils(node->right);
}
public:
BSTIterator(TreeNode *root) {
nodes = vector<int>();
BSTIteratorUtils(root);
iter = nodes.begin();
}
/** @return whether we have a next smallest number */
bool hasNext() {
return iter != nodes.end();
}
/** @return the next smallest number */
int next() {
return (*iter++);
}
};