Binary Search Tree Iterator

Design an iterator over a binary search tree with the following rules:

Elements are visited in ascending order (i.e. an in-order traversal) next() and hasNext() queries run in O(1) time in average. Have you met this question in a real interview? Yes Example For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]

   10
 /    \
1      11
 \       \
  6       12

Solution: BST inorder traversal with a stack.

public class BSTIterator {
    Stack<TreeNode> stack;
    //@param root: The root of binary tree.
    public BSTIterator(TreeNode root) {
        // write your code here
        stack = new Stack<TreeNode>();
        while(root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    //@return: True if there has next node, or false
    public boolean hasNext() {
        // write your code here
        return !stack.isEmpty();
    }

    //@return: return next node
    public TreeNode next() {
        // write your code here
        TreeNode n = stack.pop();
        if(n.right != null) {
            TreeNode p = n.right;
            while(p != null) {
                stack.push(p);
                p = p.left;
            }
        }
        return n;
    }
}

results matching ""

    No results matching ""