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, whereh is the height of the tree.
思路:依靠栈数据结构,然后中序遍历的思想
class BSTIterator {
public:
BSTIterator(BinTree *root) {
while(!st.empty())
sk.pop();
BinTree* temp=root;
while(temp != NULL)
{
sk.push(temp);
temp = temp->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return sk.empty();
}
/** @return the next smallest number */
int next() {
BinTree* res = sk.top();
sk.pop();
BinTree* temp = res->right;
while(temp != NULL)
{
sk.push(temp);
temp = temp->left;
}
return res->value;
}
private:
stack<BinTree*> sk;
};
ps:其实,这个可以看做是查找二叉查找树的前继节点和后继节点,这里我们假设二叉查找树存在parent节点,那么对于当前节点,我们先看后继节点,如果有右孩子,那么查找右子树中最左边的节点,如果没有右孩子,那么向上查找,直到找到一个节点,这个节点是其父节点的左孩子,那个这个父节点就是当前节点的后继,当然如果没有parent节点的话,我们可以在查找的时候时候栈空间记录查找的路径,栈记录的就是其祖先节点,可以使用栈中节点的记录来代替parnejt节点的作用。
接下来我们来看当前节点的前继节点,如果当前节点有左孩子,那么查找左子树的最右的节点,如果没有左子树,那么向上查找,直到找到一个节点,这个节点是其父节点的右孩子,那么这个父节点就是当前节点的前继节点,当然,如果没有parent节点的话,那么可以在查找当期节点的时候使用栈空间辅助查找。