Skip to content

Commit 3397bd5

Browse files
committed
binary_search_tree_iterator
1 parent a458820 commit 3397bd5

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
149149
#### [169. Majority Element](https://github.com/hitzzc/go-leetcode/tree/master/majority_element)
150150
#### [171. Excel Sheet Column Number](https://github.com/hitzzc/go-leetcode/tree/master/excel_sheet_column_number)
151151
#### [172. Factorial Trailing Zeroes](https://github.com/hitzzc/go-leetcode/tree/master/factorial_trailing_zeroes)
152+
#### [173. Binary Search Tree Iterator](https://github.com/hitzzc/go-leetcode/tree/master/binary_search_tree_iterator)
152153

153154

154155

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <stack>
2+
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+
private:
12+
stack<TreeNode*> stk;
13+
public:
14+
BSTIterator(TreeNode *root) {
15+
while (root != NULL){
16+
stk.push(root);
17+
root = root->left;
18+
}
19+
}
20+
21+
/** @return whether we have a next smallest number */
22+
bool hasNext() {
23+
return !stk.empty();
24+
}
25+
26+
/** @return the next smallest number */
27+
int next() {
28+
auto top = stk.top();
29+
stk.pop();
30+
int ret = top->val;
31+
top = top->right;
32+
while (top != NULL){
33+
stk.push(top);
34+
top = top->left;
35+
}
36+
return ret;
37+
}
38+
};

0 commit comments

Comments
 (0)