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.
Solutions:
首先想到的要用中序遍历。
O(n) memory的算法:
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
this->root = root;
InOrderSearch(root);
if(root == NULL) {
return;
}
}
void InOrderSearch(TreeNode *t) {
if(t == NULL) {
return;
}
if(t->left != NULL) {
InOrderSearch(t->left);
}
Q.push(t);
if(t->right != NULL) {
InOrderSearch(t->right);
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !Q.empty();
}
/** @return the next smallest number */
int next() {
int ret=Q.front()->val;
Q.pop();
return ret;
}
private:
TreeNode *root;
queue<TreeNode*> Q;
};
O(n)算法:
不用预先遍历所有节点。用一个栈保存即将要访问的节点,先入栈的后访问。每当访问一个节点时,将该节点出栈,并将其右孩子及其左链一并入队列。
从而可以实现动态更新栈内容,实现正确的中序访问次序。