当前位置:网站首页>LC173. 二叉搜索树迭代器
LC173. 二叉搜索树迭代器
2022-07-02 22:09:00 【996冲冲冲】
其实就相当于二叉搜索树的中序遍历,在next的时候返回一次结果。
所以可以直接存储中序遍历的所有结果在调用next方法时返回#方法一
class BSTIterator(object):
def __init__(self, root):
""" :type root: TreeNode """
self.queue = collections.deque()
self.inorder(root)
def inorder(self,root):
if not root:
return
self.inorder(root.left)
self.queue.append(root.val)
self.inorder(root.right)
def next(self):
""" :rtype: int """
return self.queue.popleft()
def hasNext(self):
""" :rtype: bool """
return len(self.queue) > 0
也可以用迭代的方法来进行中序遍历,将迭代法进行拆分在next中返回#方法二
class BSTIterator(object):
def __init__(self, root):
""" :type root: TreeNode """
self.stack =[]
while root:
self.stack.append(root)
root = root.left
def next(self):
""" :rtype: int """
cur = self.stack.pop()
node = cur.right
while node:
self.stack.append(node)
node = node.left
return cur.val
def hasNext(self):
""" :rtype: bool """
return len(self.stack)>0
边栏推荐
- MySQL reset password, forget password, reset root password, reset MySQL password
- antd组件upload上传xlsx文件,并读取文件内容
- [chestnut sugar GIS] ArcMap - why should the tick of classic capture be removed when using custom capture?
- How should programmers write logs
- 送给即将工作的自己
- [LeetCode] 反转字符串【344】
- [micro service sentinel] rewrite Sentinel's interface blockexceptionhandler
- 电商系统微服务架构
- [leetcode] reverse string [344]
- Zhong Xuegao responded that the product will not melt for 1 hour: it contains solid components and cannot melt into water
猜你喜欢
大话云原生之负载均衡篇-小饭馆客流量变大了
數據分析學習記錄--用EXCEL完成簡單的單因素方差分析
NC50965 Largest Rectangle in a Histogram
手写ORM(对象关系映射)增删改查
Uniapp wechat login returns user name and Avatar
odoo13搭建医院HRP环境(详细步骤)
Kubernetes uses the host name to allocate the pod on the specified node
Array advanced improvement
WebRTC音视频采集和播放示例及MediaStream媒体流解析
牛客网:龙与地下城游戏
随机推荐
Xiaopeng P7 had an accident and the airbag did not pop up. Is this normal?
【板栗糖GIS】arcscene—如何做出有高度的高程图
地方经销商玩转社区团购模式,百万运营分享
Baidu AI Cloud - create a face recognition application
Golang的学习路线
牛客网:龙与地下城游戏
杰理之、产线装配环节【篇】
高并发介绍及应对
[LeetCode] 数组中的第K个最大元素【215】
从2022年Q1财报看携程的韧性和远景
[leetcode] most elements [169]
JS syntax ES6, ES7, es8, es9, ES10, es11, ES12 new features (Abstract)
[error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
Uniapp wechat login returns user name and Avatar
Zhong Xuegao responded that the product will not melt for 1 hour: it contains solid components and cannot melt into water
P7072 [csp-j2020] live broadcast Award
Kubernetes uses the host name to allocate the pod on the specified node
悬镜安全在RSAC2022上斩获Global InfoSec Awards四项大奖
DTM distributed transaction manager PHP collaboration client V0.1 beta release!!!
Local dealers play the community group purchase mode and share millions of operations