[LintCode] Binary Search Tree Iterator

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 inaverage.  
Example

For the following binary search tree, in-order traversal by using iterator is[1, 6, 10, 11, 12]

   10
 /    \
1      11
 \       \
  6       12
Challenge

Extra memory usage O(h), h is the height of the tree.

Super Star: Extra memory usage O(1)

 

SOLUTION:

这题啊,说实话,背诵题,首先背下来,再说理解。

开始说这个题,题本身来说,不难,就是一个inorder遍历,不过要用iterator来写(这里插一句,什么是iterator呢? 迭代器基本有俩功能,next(),hasNext(),输出下一个元素,不过考虑到原始数据如果从list换成arraylist这种类似情况,而导致从新写一个for循环带来的麻烦,研究出一个迭代器,所有循环在迭代器内部完成),用iterator就是分开写这个这个程序,输出中序遍历的下一个元素。

思路就是中序遍历,具体看代码:

/**
 * 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 {
    //@param root: The root of binary tree.
    private Stack<TreeNode> stack = new Stack<TreeNode>();
    private TreeNode current;
    public BSTIterator(TreeNode root) {
        current = root;
    }

    //@return: True if there has next node, or false
    public boolean hasNext() {
        return (current != null || !stack.isEmpty());
    }
    
    //@return: return next node
    public TreeNode next() {
        while (current != null){
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        TreeNode node = current;
        current = current.right;
        return node;
    }
}
View Code

 

 

posted @ 2015-11-04 12:17  Tri_tri_tri  阅读(152)  评论(0)    收藏  举报