zoukankan      html  css  js  c++  java
  • leetcode刷题笔记一百七十三题 二叉搜索树迭代器

    leetcode刷题笔记一百七十三题 二叉搜索树迭代器

    源地址:173. 二叉搜索树迭代器

    问题描述:

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

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

    示例:

    BSTIterator iterator = new BSTIterator(root);
    iterator.next(); // 返回 3
    iterator.next(); // 返回 7
    iterator.hasNext(); // 返回 true
    iterator.next(); // 返回 9
    iterator.hasNext(); // 返回 true
    iterator.next(); // 返回 15
    iterator.hasNext(); // 返回 true
    iterator.next(); // 返回 20
    iterator.hasNext(); // 返回 false

    提示:

    next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
    你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。

    //通过定义栈,以中序遍历逆次序压入栈,随着函数调用进行弹栈即可
    /**
     * Definition for a binary tree node.
     * class TreeNode(var _value: Int) {
     *   var value: Int = _value
     *   var left: TreeNode = null
     *   var right: TreeNode = null
     * }
     */
    class BSTIterator(_root: TreeNode) {
        import scala.collection.mutable
        val stack = mutable.Stack.empty[TreeNode]
        inorder(_root)
    
        def inorder(root: TreeNode): Unit = {
            if (root == null) return
            inorder(root.right)
            stack.push(root)
            inorder(root.left)
        }
    
        /** @return the next smallest number */
        def next(): Int = {
            return stack.pop.value
        }
    
        /** @return whether we have a next smallest number */
        def hasNext(): Boolean = {
            return stack.nonEmpty
        }
    
    }
    
    /**
     * Your BSTIterator object will be instantiated and called as such:
     * var obj = new BSTIterator(root)
     * var param_1 = obj.next()
     * var param_2 = obj.hasNext()
     */
    
  • 相关阅读:
    com.panie 项目开发随笔_前后端框架考虑(2016.12.8)
    Jsoup 使用教程:数据抽取
    Jsoup 使用教程:输入
    项目中图片处理总结
    jsonp 跨域请求
    由Memcached升级到 Couchbase的 Java 客户端的过程记录(三)
    由Memcached升级到 Couchbase的 Java 客户端的过程记录(二)
    jquery eval解析JSON中的注意点介绍
    JS禁止WEB页面鼠标事件大全
    jQuery事件之鼠标事件
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13642638.html
Copyright © 2011-2022 走看看