首页 > 编程语言 > 详细

Leetcode练习(Python):栈类:第173题:二叉搜索树迭代器:实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。 调用 next() 将返回二叉搜索树中的下一个最小的数。

时间:2020-05-16 12:50:11      阅读:62      评论:0      收藏:0      [点我收藏+]

题目:

二叉搜索树迭代器:实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。  调用 next() 将返回二叉搜索树中的下一个最小的数。

思路:

二叉搜索树使用中序,然后弹出栈底。

程序:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class BSTIterator:

    def __init__(self, root: TreeNode):
        self.result = []
        if root:
            self.inorder(root)

    def inorder(self, node):
        if node.left:
            self.inorder(node.left)
        self.result.append(node.val)
        if node.right:
            self.inorder(node.right)

    def next(self) -> int:
        """
        @return the next smallest number
        """
        if self.result:
            return self.result.pop(0)

    def hasNext(self) -> bool:
        """
        @return whether we have a next smallest number
        """
        if len(self.result) > 0:
            return True
        else:
            return False

# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

  

Leetcode练习(Python):栈类:第173题:二叉搜索树迭代器:实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。 调用 next() 将返回二叉搜索树中的下一个最小的数。

原文:https://www.cnblogs.com/zhuozige/p/12898979.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!