Monday, August 17, 2015

Binary Search Tree Iterator | Leetcode

Implement 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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

---

Solution: Maintain a stack of nodes which will get a size at most equal to the height of the tree. First push the root node into the stack. Pop the top node off the stack. If this node is a leaf node, then return it. If not, push the right node, then the node itself as a leaf node (a new node), and the left node into the stack. The trick to avoid returning the same node twice is to make the current node a leaf node by removing its children, then push the new childless node back into the stack.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class BSTIterator {

    private Stack<TreeNode> stack = new Stack<>();

    public BSTIterator(TreeNode root) {
        if (root != null) stack.push(root);
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        while (true) {
            TreeNode node = stack.pop();
            
            if (node.left == null && node.right == null) {
                return node.val;
            }
            
            if (node.right != null) {
                stack.push(node.right);
            }
            
            stack.push(new TreeNode(node.val));
            
            if (node.left != null) {
                stack.push(node.left);
            }
        }
    }
}

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */

No comments: