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

173. Binary Search Tree Iterator

时间:2016-06-05 08:41:19      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 173. Binary Search Tree Iterator 
 * 2016-6-4 by Mingyang
 * 就是一个典型的DFS,保证在constructor的时候就需要保持一个stack的情况,push进去最小的那个值
 * 每次取了值以后注意不要忘了继续往stack里面push
 * return the next smallest number in the BST是值的是从零开始起return,一个一个的return
 */
class BSTIterator {
    Stack<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>();
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }
    public boolean hasNext() {
        return !stack.isEmpty();
    }
    public int next() {
        TreeNode node = stack.pop();
        int result = node.val;
        if (node.right != null) {
            node = node.right;
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
        }
        return result;
    }
}
//下面就是自己写的一次过的代码,多用了一个queue,一次性的把所有的都存起来了,一个一个取方便
 class BSTIterator1 {
    Stack<TreeNode> stack=new Stack<TreeNode>();
    Queue<TreeNode> queue=new LinkedList<TreeNode>();
    public BSTIterator1(TreeNode root) {
        TreeNode p=root;
        while(p!=null||stack.size()!=0){
            if(p!=null){
                stack.push(p);
                p=p.left;
            }else{
                TreeNode q=stack.pop();
                queue.add(q);
                p=q.right;
            }
        }
    }
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        if(queue.size()>0)
          return true;
        else
          return false;
    }
    /** @return the next smallest number */
    public int next() {
        return queue.remove().val;
    }
}

 

173. Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5560041.html

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