¡GoConqr estrena diseño! Cuéntanos qué te parece.

Fichas

Binary Search Tree Iterator

Suhas S Inglés 1 ficha

Fichas del conjunto (1)

  1. 1mplement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.public class BSTIterator {
    private Stack s;
    public BSTIterator(TreeNode root) {
    s = new Stack<>();
    TreeNode cur = root;
    while( cur != null){
    s.push(cur);
    if(cur.left != null)
    cur = cur.left;
    else
    break;
    }
    }
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
    return (!s.isEmpty());
    }
    /** @return the next smallest number */
    public int next() {
    TreeNode cur = s.pop();
    TreeNode node = cur;
    if(cur.right != null ){
    cur = cur.right;
    while(cur != null){
    s.push(cur);
    if(cur.left != null){
    cur = cur.left;
    }else break;
    }
    }
    return node.val;
    }
    }

Información

Descripción
Fichas sobre Binary Search Tree Iterator, creado por Suhas S el 28/03/2018.
Creado por
Suhas S
Visitas
0
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?