zoukankan      html  css  js  c++  java
  • Leetcode173. Binary Search Tree Iterator二叉搜索树迭代器

    实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

    调用 next() 将返回二叉搜索树中的下一个最小的数。

    注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 h 是树的高度。

    二叉树的中序遍历

    class BSTIterator {
    public:
        stack<TreeNode*> s;
        TreeNode *cur;
        BSTIterator(TreeNode *root) {
            cur = root;
            while(cur)
            {
                s.push(cur);
                cur = cur ->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !s.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            cur = s.top();
            s.pop();
            int res = cur ->val;
            cur = cur ->right;
            while(cur)
            {
                s.push(cur);
                cur = cur ->left;
            }
            return res;
        }
    };
  • 相关阅读:
    国产html编辑器
    豆瓣90mhz电台还行
    购物搜索
    linode vps 优化集锦
    这个系统,我看行,
    代理网站
    合理设置域名TTL值给网站加速
    dns切换到dnspod
    elixir usage
    JSSH介绍
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433822.html
Copyright © 2011-2022 走看看