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;
        }
    };
  • 相关阅读:
    006_02SQLite_OpenHelper
    006_01SQLite_demo
    005_01XML_Serilizer
    004_05PullParser
    004_04SharedPreferences
    004_02文件读写模式
    004_01获取SD容量
    003_01电话拨号器
    maven项目中的pom.xml
    ORACLE提示表名无效
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433822.html
Copyright © 2011-2022 走看看