-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
57 lines (50 loc) · 1.13 KB
/
Solution.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode* root) {
dfs(root);
n = nums.size();
}
bool hasNext() {
return i < n - 1;
}
int next() {
return nums[++i];
}
bool hasPrev() {
return i > 0;
}
int prev() {
return nums[--i];
}
private:
vector<int> nums;
int i = -1;
int n;
void dfs(TreeNode* root) {
if (!root) {
return;
}
dfs(root->left);
nums.push_back(root->val);
dfs(root->right);
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* bool param_1 = obj->hasNext();
* int param_2 = obj->next();
* bool param_3 = obj->hasPrev();
* int param_4 = obj->prev();
*/