Skip to content

Commit ed8e760

Browse files
author
whd
committed
upload
1 parent ac71c21 commit ed8e760

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

173 Binary Search Tree Iterator .cpp

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class BSTIterator {
11+
public:
12+
BSTIterator(TreeNode *root) {
13+
insertLeft(root);
14+
}
15+
16+
/** @return whether we have a next smallest number */
17+
bool hasNext() {
18+
return !s.empty();
19+
}
20+
21+
/** @return the next smallest number */
22+
int next() {
23+
auto res = s.top()->val;
24+
auto x = s.top();
25+
s.pop();
26+
if (x->right) {
27+
insertLeft(x->right);
28+
}
29+
return res;
30+
}
31+
private:
32+
void insertLeft(TreeNode *x) {
33+
while (x) {
34+
s.push(x);
35+
x = x->left;
36+
}
37+
}
38+
stack<TreeNode *> s;
39+
};
40+
41+
/**
42+
* Your BSTIterator will be called like this:
43+
* BSTIterator i = BSTIterator(root);
44+
* while (i.hasNext()) cout << i.next();
45+
*/

0 commit comments

Comments
 (0)