forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
173.cpp
71 lines (61 loc) · 1.41 KB
/
173.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator {
stack<TreeNode *> path;
public:
BSTIterator(TreeNode *root) {
while (root) {
path.push(root);
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !path.empty();
}
/** @return the next smallest number */
int next() {
int ans = -1;
if (hasNext()) {
TreeNode *p = path.top();
path.pop();
ans = p->val;
p = p->right;
while (p) {
path.push(p);
p = p->left;
}
}
return ans;
}
};
int main() {
/*
* 5
* / \
* 2 7
* / \ / \
* 1 4 6 8
* /
* 3
*/
TreeNode *root = new TreeNode(5);
root->left = new TreeNode(2);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(4);
root->left->right->left = new TreeNode(3);
root->right = new TreeNode(7);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(8);
BSTIterator i = BSTIterator(root);
while (i.hasNext()) cout << i.next();
cout << endl;
return 0;
}