【LeetCode】173. Binary Search Tree Iterator 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/binary-search-tree-iterator/description/
题目描述
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:

BSTIterator iterator = new BSTIterator(root);
iterator.next(); // return 3
iterator.next(); // return 7
iterator.hasNext(); // return true
iterator.next(); // return 9
iterator.hasNext(); // return true
iterator.next(); // return 15
iterator.hasNext(); // return true
iterator.next(); // return 20
iterator.hasNext(); // return false
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
题目大意
实现BST的从大到小依次输出值的操作。实现两个函数,hasNext()和next(),操作的时间复杂度是O(1),空间复杂度是O(h)。
解题方法
保存全部节点
一般地,对时间要求比较严格的,我们可以使用空间进行补偿。所以使用一个栈,在初始化的过程中,就使用中序遍历,把BST的中序遍历是有序的这个特点用上。再定义hasnext()和next()就很容易了。
对中序遍历进行了小改进,导致是降序排列的。
但是我们要注意的是,下面的做法的空间复杂度是O(N)的,所以严格来说是不符合题目要求的。
python代码如下:
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.inOrder(root)
def inOrder(self, root):
if not root:
return
self.inOrder(root.right)
self.stack.append(root.val)
self.inOrder(root.left)
def hasNext(self):
"""
:rtype: bool
"""
return len(self.stack) > 0
def next(self):
"""
:rtype: int
"""
return self.stack.pop()
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
只保留左节点
下面的做法的空间复杂度是O(h),做法是每次保存要遍历的节点的所有左孩子。这样,每次最多也就是H个节点被保存,当遍历了这个节点之后,需要把该节点的右孩子的所有左孩子放到栈里,这就是个中序遍历的过程。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.push_left(root)
def next(self):
"""
@return the next smallest number
:rtype: int
"""
node = self.stack.pop()
self.push_left(node.right)
return node.val
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return self.stack
def push_left(self, root):
while root:
self.stack.append(root)
root = root.left
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
日期
2018 年 3 月 4 日
2019 年 3 月 23 日 —— 周末也要加油呀
【LeetCode】173. Binary Search Tree Iterator 解题报告(Python)的更多相关文章
- LeetCode: Binary Search Tree Iterator 解题报告
Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...
- Java for LeetCode 173 Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)
https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary searc ...
- 【原创】leetCodeOj --- Binary Search Tree Iterator 解题报告
时间挤挤总是有的 太久不做题,脑子都生锈了.来道水题练练手 题目地址: https://leetcode.com/problems/binary-search-tree-iterator/ 题目内容: ...
- ✡ leetcode 173. Binary Search Tree Iterator 设计迭代器(搜索树)--------- java
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- leetcode 173. Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- [leetcode]173. Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- 二叉树前序、中序、后序非递归遍历 144. Binary Tree Preorder Traversal 、 94. Binary Tree Inorder Traversal 、145. Binary Tree Postorder Traversal 、173. Binary Search Tree Iterator
144. Binary Tree Preorder Traversal 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...
- 【LeetCode】173. Binary Search Tree Iterator (2 solutions)
Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...
随机推荐
- 在Kubernetes上安装Percona XtraDB集群
官方文档地址:https://www.percona.com/doc/kubernetes-operator-for-pxc/kubernetes.html 一.简介 Percona XtraDB C ...
- day05 连表查询与子查询
day05 连表查询与子查询 昨日内容回顾 表关系之一对一 换位思考之后得出两边都是不可以 要么是没有关系,要么是一对一 一对一的表关系外键虽然建在哪个都可以,但是建议建在查询频率多的表上 # 外键其 ...
- 零基础学习java------day17------缓冲字节流,转换字节流,简化流,缓冲字符流,序列化和对象流
1. 缓冲字节流 缓冲区:缓冲区实质上是一个数组.通常它是一个字节数组,但是也可以使用其他种类的数组.但是一个缓冲区不 仅仅 是一个数组.缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/写进程 ...
- 【leetcode】36. Valid Sudoku(判断能否是合法的数独puzzle)
Share Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated accordi ...
- db9串口接头的定义
这个接头都是以公头为准,所有接头还是以公头去记. RS-232端(DB9公头/针型)引脚定义 2: RXD 3:TXD 5:GND 1/4/6:内部相链接 7/8 :内部相链接 1.RS-232端 ...
- ORACLE lag,lead
oracle中想取对应列前几行或者后几行的数据时可以使用lag和lead分析函数 lag:是滞后的意思,表示本行数据是要查询的数据后面,即查询之前行的记录. lead:是领队的意思,表示本行数据是要查 ...
- VUE页面实现加载外部HTML方法
前后端分离,后端提供了接口.但有一部分数据,比较产品说明文件,是存在其他的服务器上的.所以,在页面显示的时候,如果以页面内嵌的形式显示这个说明文件.需要搞点事情以达到想要的效果.本文主要和大家介绍VU ...
- 【Linux】【Commands】基础概念及常用基础命令
命令的语法通用格式: ------------------------------------------------ #COMMAND OPTIONS ARGUMENTS 发起命令:请求内核将某个二 ...
- 热部署详细步骤---·> 小热身!
IDEA 2018.1.5 4版本 热部署 网址:https://www.jb51.net/softjc/629271.html
- centos部署golang环境
目录 一.简介 二.部署 一.简介 Go语言(或 Golang)起源于 2007 年,并在 2009 年正式对外发布.Go 是非常年轻的一门语言,它的主要目标是"兼具 Python 等动态语 ...