-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search Tree Iterator.cpp
57 lines (51 loc) · 1.07 KB
/
Binary Search Tree Iterator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include "model.h"
using namespace std;
class BSTIterator {
private:
stack<TreeNode *> s;
TreeNode *cur;
public:
BSTIterator(TreeNode *root) {
cur = root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return cur != NULL || !s.empty();
}
/** @return the next smallest number */
int next() {
while(cur != NULL) {
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
TreeNode *node = cur;
cur = cur->right;
return node->val;
}
};
TreeNode *buildTree(int depth, int val) {
TreeNode *root = new TreeNode(val);
if(depth == 0) {
return root;
}
root->left = buildTree(depth - 1, val - 1);
root->right = buildTree(depth - 1, val + 1);
return root;
}
int main() {
TreeNode *tree = buildTree(3, 5);
bfsCodec code;
string str = code.serialize(tree);
cout << str << endl;
BSTIterator it(tree);
while(it.hasNext()) {
cout << it.next() << endl;
}
return 0;
}