首页 > 编程语言 > 详细

Java-Binary Search Tree Iterator

时间:2015-01-13 14:23:04      阅读:300      评论:0      收藏:0      [点我收藏+]


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

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

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

要求实现一个能返回BST最小值的树 由于要求每次取最小值只能是O(1)复杂度 所以不能每次对BST遍历求最小值。可以使用队列 在构造函数时就将BST的结果存入队列中 之后的hasNext()和next()都根据队列的状态来 代码如下:

public class BSTIterator {
    Queue<TreeNode> res=new LinkedList<TreeNode>();
    public BSTIterator(TreeNode root) {
        inistack(root);
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
       return !res.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
       return res.poll().val;
    }
    public void inistack(TreeNode root){
        if(root==null)return;
        inistack(root.left);
        res.offer(root);
        inistack(root.right);
    }
    
}


 

 

Java-Binary Search Tree Iterator

原文:http://blog.csdn.net/u012734829/article/details/42675525

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!