zoukankan      html  css  js  c++  java
  • [LeetCode] 173. 二叉搜索树迭代器

    题目链接 : https://leetcode-cn.com/problems/binary-search-tree-iterator/

    题目描述:

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

    调用 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 中至少存在一个下一个最小的数。

    思路:

    做这道题, 先把树的中序遍历的迭代写法了解一下

    94. 二叉树的中序遍历 | 题解链接

    对,这道题就是用解决,模拟中序遍历过程!

    class BSTIterator:
    
        def __init__(self, root: TreeNode):
            self.stack = []
            self.push_stack(root)
    
        def next(self) -> int:
            """
            @return the next smallest number
            """
            tmp = self.stack.pop()
            if tmp.right:
                self.push_stack(tmp.right)
            return tmp.val
            
            
    
        def hasNext(self) -> bool:
            """
            @return whether we have a next smallest number
            """
            return bool(self.stack)
            
        def push_stack(self, node):
            while node:
                self.stack.append(node)
                node = node.left
    
  • 相关阅读:
    地区列表
    storyboard
    快捷键2
    关于本地缓存
    深入浅出Cocoa之消息
    ARC和Non-ARC下的单例模式
    runloop原理介绍
    ARC内存管理机制详解
    解决UITableViewCell separator左侧不贴边
    UICollectionView的使用
  • 原文地址:https://www.cnblogs.com/powercai/p/11328806.html
Copyright © 2011-2022 走看看