173 Binary Search Tree Iterator

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值