思路:
创建一个指针。
一直往左下找,一路上把节点都存起来。
如果直到节点为空了。当前栈顶元素就是最小值。
对于每次出站的栈顶元素,查看如果有右节点,右节点就要一路往左下找。找到最左下的就是next smallest。
Code (C++):
class BSTIterator {
public:
stack<TreeNode *> stk;
TreeNode *p;
BSTIterator(TreeNode *root) {
p = root;
while(p!=NULL)
{
stk.push(p);
p = p->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(!stk.empty()) return true;
else return false;
}
/** @return the next smallest number */
int next() {
int res;
if(!stk.empty())
{
p = stk.top();
stk.pop();
res = p->val;
p = p->right;
while(p!=NULL)
{
stk.push(p);
p = p->left;
}
}
return res;
}
};
):