Skip to content

Commit 9a12137

Browse files
committed
Binary Search Tree Iterator: in order traversal.
1 parent 2d4b9a6 commit 9a12137

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include "../Header.h"
2+
#include "../TreeNode.h"
3+
using namespace std;
4+
5+
class BSTIterator {
6+
private:
7+
stack<TreeNode*> fathers;
8+
TreeNode *iterator;
9+
public:
10+
BSTIterator(TreeNode *root) {
11+
iterator = root;
12+
if (iterator) {
13+
while (iterator->left) {
14+
fathers.push(iterator);
15+
iterator = iterator->left;
16+
}
17+
}
18+
}
19+
20+
/** @return whether we have a next smallest number */
21+
bool hasNext() {
22+
return iterator != nullptr;
23+
}
24+
25+
/** @return the next smallest number */
26+
int next() {
27+
int val = iterator->val;
28+
if (iterator->right) {
29+
iterator = iterator->right;
30+
while (iterator->left) {
31+
fathers.push(iterator);
32+
iterator = iterator->left;
33+
}
34+
}
35+
else if (!fathers.empty()) {
36+
iterator = fathers.top();
37+
fathers.pop();
38+
} else iterator = nullptr;
39+
return val;
40+
}
41+
};
42+
int main(int argc, char const *argv[])
43+
{
44+
45+
return 0;
46+
}

0 commit comments

Comments
 (0)