File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments