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