题目描述:
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false
提示:
next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。
我们知道二叉搜索树按照先序构建之后是一个递增的序列,那么 我们先按照先序放入到一个list中,之后我们就可以知道下一个有没有了
比较简单的一道中等题目。
class BSTIterator {
TreeNode root = null;
int index;
List<Integer> list = new ArrayList<>();
public BSTIterator(TreeNode root) {
this.root = root;
l(list, root);
}
public int next() {
return list.get(index ++);
}
public boolean hasNext() {
if(index == list.size()){
return false;
}
return true;
}
public void l(List<Integer> list,TreeNode root){
if(root == null){
return ;
}
l(list, root.left);
list.add(root.val);
l(list, root.right);
}
}
评论区有提到使用二叉树的莫里斯遍历,没搞清楚
当然这道题属于栈,那么可以将二叉树的中序遍历改成栈实现,代码:
class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
while(root != null){
stack.push(root);
root = root.left;
}
}
/** @return the next smallest number */
public int next() {
TreeNode node = stack.pop();
int result = node.val;
if(node.right != null){
node = node.right;
while(node != null){
stack.push(node);
node = node.left;
}
}
return result;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(stack.empty())
return false;
return true;
}
}