题目:Binary Search Tree Iterator
原题链接:https://leetcode.com/problems/binary-search-tree-iterator/
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.
设计一个二叉查找树的迭代器,迭代器的初始化用一个二叉查找树的根节点来进行。
next()函数用来返回二叉查找树中下一个最小的数值。
注意:next()和hasNext()的时间复杂度和空间复杂度应该分别限制在O( 1 )和O( h ),h是指这个二叉树的高度。
简单来说就是,按照从小到大的顺序返回二叉查找树的数值。
我们知道,对二叉查找树进行中序遍历可以得到二叉查找树的从小到大的排序序列。
所以,我们可以在初始化阶段就把这个排序序列给存起来,然后设置一个index来记录当前已经输出的元素在数组里面的下标,然后每次迭代输出时当前下标对应的元素,并让下标自加1,这个方法在next()和hasNext()函数里面无论是时间复杂度还是空间复杂度都能做到O(1),算是超额完成了题目的任务。
代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
vector<int> ans;
int index, len;
public:
void inOrder(TreeNode* root) {
if(root == NULL) return;
inOrder(root->left);
ans.push_back(root->val);
inOrder(root->right);
}
BSTIterator(TreeNode *root) {
inOrder(root);
len = ans.size();
if(!len) index = -1;
else index = 0;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(index == -1) return false;
if(index <= len - 1) return true;
else return false;
}
/** @return the next smallest number */
int next() {
return ans[index++];
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/