1. 不考虑空间复杂度,将二叉树中序遍历,插入到LinkedList中。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
private List<Integer> list = new LinkedList<Integer>();
public BSTIterator(TreeNode root) {
midSearch(root);
}
private void midSearch(TreeNode root){
if(root == null){
return;
}
midSearch(root.left);
list.add(root.val);
midSearch(root.right);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(list==null || list.size()==0){
return false;
}else{
return true;
}
}
/** @return the next smallest number */
public int next() {
int tmp = this.list.get(0);
list.remove(0);
return tmp;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
private TreeNode root;
private int outValue;
public BSTIterator(TreeNode root) {
this.root = root;
pushLeft(root);
}
private void pushLeft(TreeNode root){
if(root == null){
return;
}
stack.push(root);
pushLeft(root.left);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(stack.size()<=0){
return false;
}else{
TreeNode root = stack.pop();
outValue = root.val;
root = root.right;
while(root!=null){
stack.push(root);
root = root.left;
}
return true;
}
}
/** @return the next smallest number */
public int next() {
return outValue;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/