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

[LeetCode]173 Binary Search Tree Iterator

时间:2015-01-14 18:17:56      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/binary-search-tree-iterator/

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class BSTIterator {
    
    //
    // NOTE
    // After the iterator built, if we modify the original tree,
    // Ideally we should throw ConcurrentModificationException
    // But this need some special logic when modify tree.
    //
    // In this case, we just make assumption that
    // The iterator won‘t be effected after being built.
    
    public BSTIterator(TreeNode root) {
        
        // Validate
        stack = new Stack<>();
        pushAllLefts(root);
    }

    /** @return whether we have a next smallest number */
    // O(1) time
    // O(h) space
    public boolean hasNext() {
        return !stack.empty();
    }

    /** @return the next smallest number */
    // O(h) time
    // O(h) space
    public int next() {
        
        // Assume hasNext() == true.
        //
        // A Inorder visiting
        
        TreeNode min = stack.pop();
        
        // Can be done async
        pushAllLefts(min.right);
        
        return min.val;
    }
    
    private void pushAllLefts(TreeNode node)
    {
        while (node != null)
        {
            stack.push(node);
            node = node.left;
        }
    }
    
    private Stack<TreeNode> stack;
}

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */


[LeetCode]173 Binary Search Tree Iterator

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1603913

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