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.
Example:
BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false
Note:
next()
andhasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.- You may assume that
next()
call will always be valid, that is, there will be at least a next smallest number in the BST whennext()
is called.
思路:
1 我们将二叉树全部存储到一个vector中;2 利用stack做到一边取数一边遍历二叉树。
解法1
class BSTIterator {
public:
vector<int> nums;
BSTIterator(TreeNode* root) {
initN(root);
}
void initN(TreeNode *root) {
if (!root) return;
if (root->left) initN(root->left);
nums.push_back(root->val);
if (root->right) initN(root->right);
}
/** @return the next smallest number */
int next() {
int tmp = nums[0];
nums.erase(nums.begin());
return tmp;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return nums.size();
}
};
解法2
class BSTIterator2{
public:
BSTIterator2(TreeNode* root) {
addS(root);
}
/** @return the next smallest number */
int next() {
TreeNode *tmp = s.top();
s.pop();
if (tmp->right) addS(tmp->right);
return tmp->val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
private:
stack<TreeNode *> s;
void addS(TreeNode *root) {
while (root) {
s.push(root);
root = root->left;
}
}
};