题目:
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();
*/
本文介绍了一种二叉搜索树(BST)迭代器的设计与实现,该迭代器可以在平均O(1)的时间复杂度内返回BST中的下一个最小值,并使用O(h)的空间复杂度,其中h为树的高度。通过维护一个栈来跟踪节点,确保了高效的遍历。
817

被折叠的 条评论
为什么被折叠?



