当前位置:网站首页>Lc173. Binary search tree iterator
Lc173. Binary search tree iterator
2022-07-02 22:59:00 【996 Chong Chong】
In fact, it is equivalent to the middle order traversal of binary search tree , stay next Return a result when .
So you can directly store all the results of the middle order traversal in the call next Method # Method 1
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
You can also use the iterative method to traverse the middle order , Split the iterative method into next Back in # Method 2
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
边栏推荐
- How does Jerry test the wrong touch rate of keys [chapter]
- 世界环境日 | 周大福用心服务推动减碳环保
- Xiaopeng P7 had an accident and the airbag did not pop up. Is this normal?
- 【喜欢的诗词】好了歌
- 严守工期,确保质量,这家AI数据标注公司做到了!
- 地方经销商玩转社区团购模式,百万运营分享
- 【板栗糖GIS】arcmap—为什么使用自定义捕捉的时候,经典捕捉的勾要去掉呢?
- [LeetCode] 反转字符串【344】
- Hanging mirror security won four global infosec awards on rsac2022
- Webrtc audio and video capture and playback examples and mediastream media stream analysis
猜你喜欢
LeetCode 968. 监控二叉树
景联文科技低价策略帮助AI企业降低模型训练成本
Array advanced improvement
P1007 独木桥
【喜欢的诗词】好了歌
MySQL reset password, forget password, reset root password, reset MySQL password
[chestnut sugar GIS] how does global mapper batch produce ground contour lines through DSM
大话云原生之负载均衡篇-小饭馆客流量变大了
分享 10 个 JS 闭包面试题(图解),进来看看你能答对多少
WebRTC音视频采集和播放示例及MediaStream媒体流解析
随机推荐
How should programmers write logs
To myself who is about to work
Go four singleton modes
最小生成树 Minimum Spanning Tree
[LeetCode] 反转字符串中的单词 III【557】
Il n'est pas nécessaire d'appuyer longtemps sur la fonction de démarrage pour modifier Jelly [chapitre]
杰理之、产线装配环节【篇】
Wait to solve the zombie process
Qt QSplitter拆分器
【板栗糖GIS】arcmap—为什么使用自定义捕捉的时候,经典捕捉的勾要去掉呢?
E-commerce system microservice architecture
高并发介绍及应对
Go语言sqlx库操作SQLite3数据库增删改查
Solve the error of changing the selected file when uploading excel file. Net:: err_ UPLOAD_ FILE_ CHANGED
WebRTC音视频采集和播放示例及MediaStream媒体流解析
【硬件】标准阻值的由来
[leetcode] reverse the word III in the string [557]
【板栗糖GIS】global mapper 如何通过dsm批量制作贴地等高线
P7072 [CSP-J2020] 直播获奖
Mask R-CNN