forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTreeIterator.h
101 lines (92 loc) · 2.54 KB
/
BinarySearchTreeIterator.h
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
Author: king, [email protected]
Date: Dec 29, 2014
Problem: Binary Search Tree Iterator
Difficulty: Easy
Source: https://oj.leetcode.com/problems/binary-search-tree-iterator/
Notes:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Solution: 1. Inorder traversal use stack.
2. Morris Inorder Traversal.
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator_1 {
public:
BSTIterator(TreeNode *root) {
node = root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if (stk.empty() == true && node == NULL) return false;
return true;
}
/** @return the next smallest number */
int next() {
if (stk.empty() == true && node == NULL) return 0;
while (node != NULL) {
stk.push(node);
node = node->left;
}
int res = 0;
node = stk.top();
stk.pop();
res = node->val;
node = node->right;
return res;
}
private:
TreeNode * node;
stack<TreeNode*> stk;
};
class BSTIterator_2 {
public:
BSTIterator(TreeNode *root) {
node = root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return node != NULL;
}
/** @return the next smallest number */
int next() {
if (node == NULL) return 0;
int res = 0;
while (node != NULL) {
if (node->left == NULL) {
res = node->val;
node = node->right;
return res;
}
TreeNode * pre = node->left;
while (pre->right != NULL && pre->right != node)
pre = pre->right;
if (pre->right == NULL) {
pre->right = node;
node = node->left;
} else {
res = node->val;
node = node->right;
pre->right = NULL;
return res;
}
}
return res;
}
private:
TreeNode * node;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/