当前位置:网站首页>Sword finger offer II 055. Binary search tree iterator (medium binary search tree iterator)
Sword finger offer II 055. Binary search tree iterator (medium binary search tree iterator)
2022-07-28 22:20:00 【Calm in the wind and rain】
The finger of the sword Offer II 055. Binary search tree iterator
Implement a binary search tree iterator class BSTIterator , Represents a binary search tree traversed in middle order (BST) The iterator :
BSTIterator(TreeNode root) initialization BSTIterator An object of class .BST The root node root Will be given as part of the constructor . The pointer should be initialized to a value that does not exist in BST Number in , And the number is less than BST Any element in .
boolean hasNext() If there is a number traversing to the right of the pointer , Then return to true ; Otherwise return to false .
int next() Move the pointer to the right , Then return the number at the pointer .
Be careful , The pointer is initialized to a value that does not exist in BST Number in , So for next() The first call of will return BST The smallest element in .
It can be assumed next() The call is always valid , in other words , When calling next() when ,BST There is at least one next number in the middle order traversal of .
Example :

Input
inputs = [“BSTIterator”, “next”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”]
inputs = [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
explain
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
Tips :
The number of nodes in the tree is in the range [1, 105] Inside
0 <= Node.val <= 106
Call at most 105 Time hasNext and next operation
Advanced :
Can you design a solution that meets the following conditions ?next() and hasNext() The average time complexity of operation is O(1) , And use O(h) Memory . among h Is the height of the tree .
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/kTOapQ
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
analysis
The subject itself is not difficult , Mainly consider how to achieve advanced conditions .
First of all, you can refer to 53 How to solve the problem :https://blog.csdn.net/weixin_43942435/article/details/124079105
The next value of the current node can be found by iteration , But it is obviously inefficient to record the current node every time and then iterate from the root node , Then we consider saving the traversed nodes , The iterated nodes are saved by stack , Only iterate the effective path each time .
Answer key (Java)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class BSTIterator {
private TreeNode root;
private Deque<TreeNode> stack;
public BSTIterator(TreeNode root) {
this.root = root;
stack = new LinkedList<>();
}
public int next() {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();// Take out the target node
int val = root.val;
root = root.right;// Point to the next node ( Maybe not )
return val;
}
public boolean hasNext() {
return root != null || !stack.isEmpty();
}
}
/** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
边栏推荐
猜你喜欢
随机推荐
lotus 1.16.0 延长扇区过期时间
2021 mathematical modeling group B code
Lvs+keepalived high availability deployment practical application
第 8 篇:创建摄像机类
2021 mathematical modeling group B exercise
JS DOM编程之平平无奇小练习
SSH password free login
Oracle triggers
What is a prime factor? In number theory, a prime factor (prime factor or prime factor) refers to a prime number that can divide a given positive integer
AimBetter洞察您的数据库,DPM 和 APM 解决方案
Official document of kubevela 1.4.x
Desai wisdom number - line chart (stacking area chart): ranking of deposits of different occupational groups in the proportion of monthly income in 2022
Byte side: can TCP and UDP use the same port?
What testing services do third-party software testing institutions provide? Charging standard of software test report
腾讯云数据库负责人借了一亿元炒股?知情人士:金额不实
ECMASript 5/6 笔记
Lin Xiaobin, head of Tencent cloud database, borrowed 100 million yuan to speculate in stocks? Insider: the amount is not true
tutorial/detailed_ workflow. Ipynb quantitative finance qlib Library
04.toRef 默认值
Data visualization news, different forms of news reports




![[CS231N]Lecture_ 2:Image Classification pipelin](/img/4f/de56b071560ada746c587a9dbc5f02.jpg)



![[NLP] generate word cloud](/img/c4/4e9707bba58732a90d1c30312719a3.png)
