Skip to content

Commit 7283f65

Browse files
committed
"Binary Search Tree Iterator"
1 parent 6321305 commit 7283f65

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
127127
| 186 | [Reverse Words in a String II]| |
128128
| 179 | [Largest Number] | [C](src/179.c) |
129129
| 174 | [Dungeon Game] | |
130-
| 173 | [Binary Search Tree Iterator] | |
130+
| 173 | [Binary Search Tree Iterator] | [C++](src/173.cpp) |
131131
| 172 | [Factorial Trailing Zeroes] | [C](src/172.c) |
132132
| 171 | [Excel Sheet Column Number] | [C](src/171.c) |
133133
| 170 | [Two Sum III - Data structure design]| |

src/173.cpp

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <iostream>
2+
#include <stack>
3+
4+
using namespace std;
5+
6+
struct TreeNode {
7+
int val;
8+
TreeNode *left;
9+
TreeNode *right;
10+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
};
12+
13+
class BSTIterator {
14+
stack<TreeNode *> path;
15+
public:
16+
BSTIterator(TreeNode *root) {
17+
while (root) {
18+
path.push(root);
19+
root = root->left;
20+
}
21+
}
22+
23+
/** @return whether we have a next smallest number */
24+
bool hasNext() {
25+
return !path.empty();
26+
}
27+
28+
/** @return the next smallest number */
29+
int next() {
30+
int ans = -1;
31+
if (hasNext()) {
32+
TreeNode *p = path.top();
33+
path.pop();
34+
ans = p->val;
35+
p = p->right;
36+
while (p) {
37+
path.push(p);
38+
p = p->left;
39+
}
40+
}
41+
return ans;
42+
}
43+
};
44+
45+
int main() {
46+
/*
47+
* 5
48+
* / \
49+
* 2 7
50+
* / \ / \
51+
* 1 4 6 8
52+
* /
53+
* 3
54+
*/
55+
56+
TreeNode *root = new TreeNode(5);
57+
root->left = new TreeNode(2);
58+
root->left->left = new TreeNode(1);
59+
root->left->right = new TreeNode(4);
60+
root->left->right->left = new TreeNode(3);
61+
62+
root->right = new TreeNode(7);
63+
root->right->left = new TreeNode(6);
64+
root->right->right = new TreeNode(8);
65+
66+
BSTIterator i = BSTIterator(root);
67+
while (i.hasNext()) cout << i.next();
68+
cout << endl;
69+
70+
return 0;
71+
}

0 commit comments

Comments
 (0)