173 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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide Tags Tree Stack
这个问题是求binary search tree (BST)中的最小值问题,先要判断有没有最小值,再取最小值。首先看一下binary search tree二叉搜索树,这个树的结构特点是所有根节点的左子叶下面的值小于根节点,所有根节点右子叶下面的值大于根节点,因此这棵树很容易搜索最值。在搜索最小值的时候,先把根节点开始的左子叶放入栈中,那么这时栈顶的元素(假设为a)就是最小值。当寻找下一个最小值时就不是栈内的下一个元素了(假设为b),这时a为b的左子叶,当a存在有子叶时,a右子叶下面的值一定小于b的值,因为a为b左子叶。所以这时还需要将a的右子叶及右子叶下的所有左子叶压栈。这样设计就很巧妙,每次寻找从栈顶取元素,同时将右子叶及右子叶下的所有左子叶压栈,保证栈顶一定是最小值。
class BSTIterator {
public:
stack<TreeNode *> snode;
TreeNode * t;
BSTIterator(TreeNode *root) {
t=root;
while(t!=NULL)
{
snode.push(t);
t=t->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(snode.empty())
return false;
else
return true;
}
/** @return the next smallest number */
int next() {
int result;
t = snode.top();
result=t->val;
snode.pop();
if(t->right != NULL){
t = t->right;
while(t){
snode.push(t);
t = t->left;
}
}
return result;
}
};