173. 二叉搜索树迭代器
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。调用 next() 将返回二叉搜索树中的下一个最小的数。
暴力法求解
class BSTIterator {
List<Integer> res;
public BSTIterator(TreeNode root) {
res = new ArrayList<Integer>();
preorder(res,root);
}
public int next() {
Iterator<Integer> it = res.iterator();
int min = 65535;
while(it.hasNext()){
int a = it.next();
if( a < min ){
min = a;
}
}
res.remove(new Integer(min));
return min;
}
public boolean hasNext() {
if( res.size() == 0 ){
return false;
}
return true;
}
public void preorder(List<Integer> res , TreeNode root) {
if(root == null) return;
res.add(root.val);
preorder(res,root.left);
preorder(res,root.right);
}
}