实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
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
可以看出本题是中序遍历二叉树的应用。
注意点:正常二叉树结构 、单叉树结构都需要考虑。
考虑实时计算,而不是直接计算出结果然后存储。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BSTIterator {
private ArrayDeque<Integer> queue = new ArrayDeque();
public BSTIterator(TreeNode root) {
if(root == null){
return;
}
Stack<TreeNode> stack = new Stack();
TreeNode curr = root;
while(curr != null || !stack.isEmpty()){
while(curr != null){
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
queue.add(curr.val);
curr = curr.right;
}
}
/** @return the next smallest number */
public int next() {
if(!queue.isEmpty()){
return queue.pop();
}
return 0;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return queue.size() > 0;
}
}
/**
* 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();
*/
来源:CSDN
作者:qq_35356190
链接:https://blog.csdn.net/qq_35356190/article/details/104046047