Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Callingnext()will return the next smallest number in the BST.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class BSTIterator {
    private Stack<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>();
        TreeNode p = root;

        while(p != null) {
            stack.push(p);
            p = p.left;
        }
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode n = stack.pop();
        int res = n.val;

        if(n.right != null) {
            TreeNode p = n.right;
            while(p != null) {
                stack.push(p);
                p = p.left;
            }
        }

        return res;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.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();
 */

results matching ""

    No results matching ""