题目描述


题目链接
https://leetcode.com/problems/binary-search-tree-iterator/
方法思路
Approach:using Queue
class BSTIterator {
//Runtime: 59 ms, faster than 91.88%
//Memory Usage: 52.7 MB, less than 9.65%
TreeNode node;
Queue<TreeNode> queue;
public BSTIterator(TreeNode root) {
node = root;
queue = new LinkedList<>();
dfs(root);
}
/** @return the next smallest number */
public int next() {
return queue.poll().val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(queue.peek() != null)
return true;
return false;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
queue.offer(root);
dfs(root.right);
}
}
本文介绍了一种使用队列实现二叉搜索树迭代器的方法。通过深度优先遍历将节点依次加入队列,实现了返回下一个最小数值的功能,并判断是否还有下一个最小数。
818

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



