题目:
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.
思路:
其实这道题目本质上就是BST的先序遍历问题。我们需要维护一个栈,栈顶元素就是当前迭代器所处的位置。每次出栈一个元素后,我们需要将栈顶元素的右孩子的所有左孩子依次加入栈中。算法的平均时间复杂度是O(1),空间复杂度是O(h),其中h是树的高度。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
TreeNode* node = root;
while (node != NULL) {
st.push(node);
node = node->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !st.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *node = st.top();
st.pop();
int ret = node->val;
node = node->right;
while (node != NULL) {
st.push(node);
node = node->left;
}
return ret;
}
private:
stack<TreeNode*> st;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/