173-Binary-Search-Tree-Iterator
Last updated
Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BSTIterator {
LinkedList<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack=new LinkedList<>();
while(root!=null){
stack.offerLast(root);
root=root.left;
}
}
/** @return the next smallest number */
public int next() {
// int result;
TreeNode cur=stack.pollLast();
int result=cur.val;
cur=cur.right;
/**
我们首先通过非递归的中序遍历完成了题目的操作,非递归的中序遍历就不用我多说了吧。
在遇到一个节点时,是需要把当前节点的所有左子节点压入到栈中的。在最坏情况下,空间复杂度达到O(N),当然此时树的高度也为N。
压入所有子节点的操作是通过循环完成了,也就是说这个循环最多执行n次。
那么我们最多执行n次next操作就能完成树的遍历,平均下来的时间复杂度也就达到了O(n)/n=O(1)的要求
*/
while(cur!=null){
stack.offerLast(cur);
cur=cur.left;
}
return result;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
}
/**
* 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();
*/