-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathbinary-search-tree-iterator(AC).cpp
More file actions
71 lines (65 loc) · 1.57 KB
/
binary-search-tree-iterator(AC).cpp
File metadata and controls
71 lines (65 loc) · 1.57 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// O(1) with hashing, which requires O(n) time for preprocessing
#include <unordered_map>
#include <vector>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Example of iterate a tree:
* Solution iterator = Solution(root);
* while (iterator.hasNext()) {
* TreeNode * node = iterator.next();
* do something for node
*/
class Solution {
public:
//@param root: The root of binary tree.
Solution(TreeNode *root) {
if (root == NULL) {
cur = NULL;
return;
}
vector<TreeNode *> v;
inorder(root, v);
int n = v.size();
int i;
for (i = 1; i < n; ++i) {
nextNode[v[i - 1]] = v[i];
}
nextNode[v[n - 1]] = NULL;
cur = v[0];
}
//@return: True if there has next node, or false
bool hasNext() {
// write your code here
return cur != NULL;
}
//@return: return next node
TreeNode* next() {
TreeNode *ptr = cur;
cur = nextNode[cur];
return ptr;
}
~Solution() {
nextNode.clear();
}
private:
unordered_map<TreeNode *, TreeNode *> nextNode;
TreeNode *cur;
void inorder(TreeNode *root, vector<TreeNode *> &v) {
if (root == NULL) {
return;
}
inorder(root->left, v);
v.push_back(root);
inorder(root->right, v);
}
};