-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst_iterator.cpp
55 lines (52 loc) · 1.24 KB
/
bst_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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
TreeNode *curr;
stack<TreeNode *> S;
public:
BSTIterator(TreeNode* root) {
if (root != NULL) {
curr = root;
S.push(root);
while (curr->left != NULL) {
curr = curr->left;
S.push(curr);
}
curr = S.top();
}
}
/** @return the next smallest number */
int next() {
int ans = curr->val;
S.pop();
if (curr->right != NULL) {
curr = curr->right;
S.push(curr);
while (curr->left != NULL) {
curr = curr->left;
S.push(curr);
}
}
if (hasNext())
curr = S.top();
return ans;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !S.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/