GoConqr hat ein neues Design! Sag uns, wie es dir gefällt.

Karteikarten

Binary Search Tree Iterator

Suhas S Englisch 1 Karte

Karten in diesem Stapel (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;
    }
    }

Informationen

Beschreibung
Karteikarten am Binary Search Tree Iterator, erstellt von Suhas S am 28/03/2018.
Erstellt von
Suhas S
Aufrufe
0
Bewertung

Feedback

Worum geht es?

Wie gefällt dir das neue Design?

Dein Eindruck