Descripción del título
Iterador del árbol de búsqueda binario
Código AC
Al leer la pregunta, es fácil pensar en usar el recorrido en orden para hacer, pero combinado con la limitación de la pregunta, esta pregunta no es adecuada para usar el recorrido en orden directamente. Debe simularse a través de la pila del recorrido en orden del árbol.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BSTIterator {
Stack<TreeNode> stk=new Stack<>();
public BSTIterator(TreeNode root) {
while(root!=null){
stk.push(root);
root=root.left;
}
}
/** @return the next smallest number */
public int next() {
TreeNode p=stk.peek();
int val=p.val;
stk.pop();
p=p.right;
while(p!=null){
stk.push(p);
p=p.left;
}
return val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stk.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();
*/