Skip to content

Commit da5e64f

Browse files
Create bst_iterator.cpp
1 parent 5951e01 commit da5e64f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

bst_iterator.cpp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class BSTIterator {
13+
private:
14+
stack<TreeNode*> st;
15+
public:
16+
BSTIterator(TreeNode *root) {
17+
find_left(root);
18+
}
19+
20+
/** @return whether we have a next smallest number */
21+
bool hasNext() {
22+
if (st.empty())
23+
return false;
24+
return true;
25+
}
26+
27+
/** @return the next smallest number */
28+
int next() {
29+
TreeNode* top = st.top();
30+
st.pop();
31+
if (top->right != NULL)
32+
find_left(top->right);
33+
34+
return top->val;
35+
}
36+
37+
/** put all the left child() of root */
38+
void find_left(TreeNode* root)
39+
{
40+
TreeNode* p = root;
41+
while (p != NULL)
42+
{
43+
st.push(p);
44+
p = p->left;
45+
}
46+
}
47+
};
48+
49+
/**
50+
* Your BSTIterator object will be instantiated and called as such:
51+
* BSTIterator* obj = new BSTIterator(root);
52+
* int param_1 = obj->next();
53+
* bool param_2 = obj->hasNext();
54+
*/

0 commit comments

Comments
 (0)