GoConqr has a new look! Let us know what you think.

Flashcards

Binary Search Tree Iterator

Suhas S English 1 card

Cards in this deck (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;
    }
    }

Information

Description
Flashcards on Binary Search Tree Iterator, created by Suhas S on 28/03/2018.
Created by
Suhas S
Views
0
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?