Description

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
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
  1. 对于一个当前tree node(从root开始),从上往下遍历它整个左分支的所有左节点放入stack中,这样pop出来的时候是从下往上pop符合in order的顺序
  2. 每pop出来一个node,意味着它的整个左分支都被pop过了,这时把当前node的value放入result list中,对node的right节点做步骤1的操作,讲右分支放入stack
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 * Example of iterate a tree:
 * BSTIterator iterator = new BSTIterator(root);
 * while (iterator.hasNext()) {
 *    TreeNode node = iterator.next();
 *    do something for node
 * } 
 */
public class BSTIterator {
    Stack<TreeNode> stack;

    private void PushNodeIntoStack(TreeNode node) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
    }

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

    //@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 next = stack.pop();
        PushNodeIntoStack(next.right);
        return next;
    }
}

results matching ""

    No results matching ""