Skip to content

Commit 1f32de2

Browse files
committed
Add Q173
1 parent 7ccd96b commit 1f32de2

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
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+
while (root) {
14+
s.push(root);
15+
root = root->left;
16+
}
17+
}
18+
19+
/** @return whether we have a next smallest number */
20+
bool hasNext() {
21+
return !s.empty();
22+
}
23+
24+
/** @return the next smallest number */
25+
int next() {
26+
TreeNode *t = s.top();
27+
s.pop();
28+
int val = t->val;
29+
t = t->right;
30+
while (t) {
31+
s.push(t);
32+
t = t->left;
33+
}
34+
return val;
35+
}
36+
37+
private:
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)