-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path173.cpp
More file actions
36 lines (32 loc) · 715 Bytes
/
Copy path173.cpp
File metadata and controls
36 lines (32 loc) · 715 Bytes
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
class BSTIterator {
public:
stack<TreeNode *> s;
int size;
BSTIterator(TreeNode *root) {
size = 0;
PushAllLeft(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return size > 0;
}
/** @return the next smallest number */
int next() {
if (size <= 0)
return 0;
TreeNode *temp = s.top();
int &ret = temp->val;
s.pop();
--size;
if (temp->right)
PushAllLeft(temp->right);
return ret;
}
void PushAllLeft(TreeNode *node) {
while (node) {
s.push(node);
node = node->left;
++size;
}
}
};