当前位置:网站首页>173. Binary Search Tree Iterator
173. Binary Search Tree Iterator
2022-06-23 08:24:00 【ujn20161222】
Medium
5062360Add to ListShare
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root)Initializes an object of theBSTIteratorclass. Therootof the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.boolean hasNext()Returnstrueif there exists a number in the traversal to the right of the pointer, otherwise returnsfalse.int next()Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Example 1:

Input ["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] Output [null, 3, 7, true, 9, true, 15, true, 20, false] Explanation BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False
Constraints:
- The number of nodes in the tree is in the range
[1, 105]. 0 <= Node.val <= 106- At most
105calls will be made tohasNext, andnext.
Follow up:
- Could you implement
next()andhasNext()to run in averageO(1)time and useO(h)memory, wherehis the height of the tree?
Accepted
514,332
Submissions
787,637
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.stack=[]
self.curr=root
def next(self) -> int:
while self.curr:
self.stack.append(self.curr)
self.curr=self.curr.left
self.curr=self.stack.pop()
out=self.curr.val
self.curr=self.curr.right
return out
def hasNext(self) -> bool:
return self.stack or self.curr
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()边栏推荐
- List interface three sub implementation classes
- How can I handle the "unable to load" exception when easyplayer plays webrtcs?
- Structure and usage of transform
- 6-闪耀的激光-CALayer 的应用
- Flutter achieves the effect of selecting seats in the cinema!
- Why use growth neural gas network (GNG)?
- 词性家族
- 单编内核驱动模块
- Map interface and its sub implementation classes
- Set the time zone in ci4 (CodeIgniter 4)
猜你喜欢

Qualcomm 9x07 two startup modes

自组织映射神经网络(SOM)

Install a WGet for your win10

Object. Defineproperty() and data broker

Object.defineProperty() 和 数据代理

Does huangrong really exist?

81 sentences worth repeating

Summary of communication mode and detailed explanation of I2C drive

论文阅读【Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset】

Deep learning ----- different methods to implement lenet-5 model
随机推荐
【云计算】GFS思想优势以及架构
USB peripheral driver - configfs
Single core driver module
“方脸老师”董宇辉再回应热度下降:把农产品直播做好让农民受益 考虑去支教
Kernel log debugging method
Cloud computing "half peak"
What are open source software, free software, copyleft and CC? Can't you tell them clearly?
Deep learning ----- different methods to implement lenet-5 model
Open source technology exchange batch stream integrated data synchronization engine Chunjun data restore DDL function module analysis
On the light application platform finclip and the mobile application development platform mpaas
Leetcode 173 Binary search tree iterator (2022.06.22)
Easygbs cannot play video streams in webrtc format. What is the reason?
1-gradients, shadows, and text
Multi Chain and cross chain are the future
[operating steps] how to set the easynvr hardware device to be powered on without automatic startup?
Summary of communication mode and detailed explanation of I2C drive
训练后的随机森林模型导出和加载
Why use growth neural gas network (GNG)?
点云库pcl从入门到精通 第十章
Set the time zone in ci4 (CodeIgniter 4)