题目描述:
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 BSTIterator {
Stack<TreeNode> stack;
Set<TreeNode> visited;
public BSTIterator(TreeNode root) {
stack=new Stack<TreeNode>();
visited=new HashSet<TreeNode>();
stack.add(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(!stack.isEmpty()){
return stack.peek()==null?false:true;
}
return false;
}
public int next() {
TreeNode node=stack.peek();
while(node.left!=null&&!visited.contains(node.left)){
stack.add(node.left);
node=node.left;
}
node=stack.pop();
if(node.right!=null&&!visited.contains(node.right))
stack.add(node.right);
visited.add(node);
return node.val;
}
}
本文介绍了一种针对二叉搜索树(BST)的迭代器实现方法,该方法能够高效地找到并返回树中下一个最小值。通过不断向左遍历节点,并利用栈结构辅助记录,确保了平均O(1)的时间复杂度和O(h)的空间复杂度,其中h为树的高度。
817

被折叠的 条评论
为什么被折叠?



