forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-search-tree-iterator_2(AC).cpp
More file actions
65 lines (62 loc) · 1.44 KB
/
binary-search-tree-iterator_2(AC).cpp
File metadata and controls
65 lines (62 loc) · 1.44 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
// O(h) time and O(1) space
/**
* 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) {
this->root = root;
if (root == NULL) {
cur = NULL;
return;
}
cur = root;
while (cur->left != NULL) {
cur = cur->left;
}
}
//@return: True if there has next node, or false
bool hasNext() {
return cur != NULL;
}
//@return: return next node
TreeNode* next() {
TreeNode *ans = cur;
if (cur->right != NULL) {
cur = cur->right;
while (cur->left != NULL) {
cur = cur->left;
}
return ans;
}
TreeNode *p1 = root;
TreeNode *p2 = NULL;
while (p1->val != cur->val) {
if (cur->val < p1->val) {
p2 = p1;
p1 = p1->left;
} else {
p1 = p1->right;
}
}
cur = p2;
return ans;
}
private:
TreeNode *root, *cur;
};