-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path173.cpp
More file actions
58 lines (48 loc) · 1.41 KB
/
173.cpp
File metadata and controls
58 lines (48 loc) · 1.41 KB
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
// 173. Binary Search Tree Iterator
// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
// Using stack to implement iterator. First go to the leftmost node, then everytime pop a node, if that node has a right node,
// then push until the leftmost one. Otherwise, do nothing.
/**
* 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 {
public:
stack<TreeNode*> stack1;
BSTIterator(TreeNode* root) {
TreeNode* curr = root;
while(curr){
stack1.push(curr);
curr = curr->left;
}
}
/** @return the next smallest number */
int next() {
TreeNode* curr = stack1.top();
stack1.pop();
int ans = curr->val;
if (curr->right){
curr = curr->right;
while(curr){
stack1.push(curr);
curr=curr->left;
}
}
return ans;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !stack1.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();
*/