码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Binary Search Tree Iterator

时间:2015-11-04 13:05:55      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

[LintCode] Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/tritritri/p/4935577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!