由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 请问leetcode的Binary Search Tree Iterator
相关主题
攒个人品发碗F家面筋面完G的电面了,忐忑
请问怎样写没有parent pointer的BST iterator?问到G家题
刷了半天题这周一的G家onsite,虽然挂了,还是发个面筋攒人品吧
LC的BST iterator到底要考察什么?【代发】g家面筋
这个check whether a binary tree is a BST or not攒人品,amazon一面经历
bst中序遍历c++ class iterator如何判断两个BST的元素是一样的?
G电面面经:BT的iterator inorder traversal问个题
Uber 面经iterator 实现 如何 peek(),pop()?
相关话题的讨论汇总
话题: next话题: treenode话题: stack话题: return
进入JobHunting版参与讨论
1 (共1页)
c***u
发帖数: 4107
1
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.
Note: next() and hasNext() should run in average O(1) time and uses O(h)
memory, where h is the height of the tree.
高人的程序是:
public class BSTIteratorInorder {
private Stack stack = new Stack<>();

public BSTIteratorInorder(TreeNode root) {
pushLeftChildren(root); // find the first node (leftmost) to start,
and store the trace
}
// push all the left subnodes to stack until reaching the first node in
inorder (the leftmost node)
private void pushLeftChildren(TreeNode curr) {
while (curr != null) {
stack.add(curr);
curr = curr.left;
}
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
if (!hasNext()) throw new NoSuchElementException("All nodes have
been visited");

TreeNode res = stack.pop();
pushLeftChildren(res.right);
return res.val;
}
}
我看说, next() should run in O(1) time, 但是上面这个程序, next()不是O(1)啊.
虽然 res = stack.pop(), return res.val是 O(1), 但是这个next()
函数中间, 还有一个入栈的动作pushLeftChildren(res.right), 这个本身是O(h), 那
next()这个函数整体就是O(h)???
b*****n
发帖数: 618
2
amortized O(1)
Q**g
发帖数: 183
3
amortized average。每个node最多入栈一次,加上n+1个null指针每个尝试一下怎么都
不会超过O(n)。next n 回平均就是O(1)了。

be
,

【在 c***u 的大作中提到】
: 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.
: Note: next() and hasNext() should run in average O(1) time and uses O(h)
: memory, where h is the height of the tree.
: 高人的程序是:
: public class BSTIteratorInorder {
: private Stack stack = new Stack<>();
:
: public BSTIteratorInorder(TreeNode root) {

1 (共1页)
进入JobHunting版参与讨论
相关主题
iterator 实现 如何 peek(),pop()?这个check whether a binary tree is a BST or not
Scala怎么通过index访问set或者arraybst中序遍历c++ class iterator
问一道C++ template的面试题G电面面经:BT的iterator inorder traversal
请教 Iterator 一题Uber 面经
攒个人品发碗F家面筋面完G的电面了,忐忑
请问怎样写没有parent pointer的BST iterator?问到G家题
刷了半天题这周一的G家onsite,虽然挂了,还是发个面筋攒人品吧
LC的BST iterator到底要考察什么?【代发】g家面筋
相关话题的讨论汇总
话题: next话题: treenode话题: stack话题: return