LeetCode173——二叉搜索树迭代器
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/binary-search-tree-iterator/description/
题目描述:
知识点:二叉搜索树、栈
思路:中序遍历的分段实现
本题的中文翻译出错,原英文如下:
next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
正确的翻译应该是next()和hashNext()的平均时间复杂度是O(1),这说明有时候我们的时间复杂度可以达到O(n)或O(h),其中n为树中的节点个数。
一开始我的思路是,先中序遍历该树,将结果保存在一个List集合里,再输出即可,但这样无法满足O(h)的内存要求。
联想LeetCode094——二叉树的中序遍历中的思路三和思路四,我们其实可以实现分段中序遍历。
在构造函数中,我们的cur指针一直往左走,寻找到最小值。
而对于next()函数,弹出栈顶元素,该元素的val值即next需返回的值,但我们还需要更新维护我们的栈。如果栈顶元素的右孩子不为null,我们需要对其右子树部分进行和构造函数中同样的入栈操作。
以上两步本质上就是LeetCode094——二叉树的中序遍历中思路三和思路四的分段实现。
next()函数的平均时间复杂度是O(1)。
hashNext()函数的时间复杂度是O(1)。
空间复杂度是O(h)。
JAVA代码:
public class BSTIterator {
private LinkedList<TreeNode> stack = new LinkedList<>();
public BSTIterator(TreeNode root) {
TreeNode cur = root;
pushToStack(cur);
}
public int next() {
TreeNode node = stack.pop();
TreeNode cur = node;
if(null != cur.right){
cur = cur.right;
pushToStack(cur);
}
return node.val;
}
public boolean hasNext() {
return !stack.isEmpty();
}
private void pushToStack(TreeNode treeNode){
TreeNode cur = treeNode;
while(cur != null){
stack.push(cur);
if(cur.left != null)
cur = cur.left;
else
break;
}
}
}
LeetCode解题报告: