Binary Search Tree Iterator 07/28
Design an iterator over a binary search tree with the following rules:
Elements are visited in ascending order (i.e. an in-order traversal)
next()
andhasNext()
queries run in O(1) time in average.
Have you met this question in a real interview? Yes
Example
For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
10
/ \
1 11
\ \
6 12
Challenge
Extra memory usage O(h), h is the height of the tree.
Super Star: Extra memory usage O(1)空间和时间复杂度 不满足条件
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* Example of iterate a tree:
* BSTIterator iterator = new BSTIterator(root);
* while (iterator.hasNext()) {
* TreeNode node = iterator.next();
* do something for node
* }
*/
public class BSTIterator {
/*
* @param root: The root of binary tree.
*/
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
// do intialization if necessary
this.stack = new Stack<>();
while(root!= null){
stack.push(root);
root = root.left;
}
}
/*
* @return: True if there has next node, or false
*/
public boolean hasNext() {
// write your code here
return !stack.isEmpty();
}
/*
* @return: return next node
*/
public TreeNode next() {
// write your code here
TreeNode node = stack.pop();
if(node.right != null){
TreeNode right = node.right;
while(right!=null){
stack.push(right);
right = right.left;
}
}
return node;
}
}
Morris Traversal 非递归,不用stack,O(1 )空间复杂度
Last updated