-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path173_Binary Search Tree Iterator.cpp
More file actions
54 lines (43 loc) · 1.08 KB
/
Copy path173_Binary Search Tree Iterator.cpp
File metadata and controls
54 lines (43 loc) · 1.08 KB
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
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
create(root);
currIndex = -1; size = sortedNodes.size();
}
/** @return whether we have a next smallest number */
bool hasNext() {
return currIndex + 1 < size;
}
/** @return the next smallest number */
int next() {
return (sortedNodes[++currIndex])->val;
}
private:
void create(TreeNode *p){
if (p){
create(p->left);
sortedNodes.push_back(p);
create(p->right);
}
}
int currIndex, size;
vector<TreeNode*> sortedNodes;
};
int main() {
TreeNode *node1 = new TreeNode(1);
TreeNode *node2 = new TreeNode(2);
TreeNode *node3 = new TreeNode(3);
node2->left = node1; node2->right = node3;
BSTIterator i = BSTIterator(node2);
while (i.hasNext()) cout << i.next();
return 0;
}