173 Binary Search Tree Iterator 二叉搜索树迭代器

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 h 是树的高度。

详见:https://leetcode.com/problems/binary-search-tree-iterator/description/

Java实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class BSTIterator {
    
    private Stack<TreeNode> stk=new Stack<TreeNode>();
    public BSTIterator(TreeNode root) {
        while(root!=null){
            stk.push(root);
            root=root.left;
        }
    }
    
    /** @return the next smallest number */
    public int next() {
        TreeNode node=stk.pop();
        int val=node.val;
        if(node.right!=null){
            node=node.right;
            while(node!=null){
                stk.push(node);
                node=node.left;
            }
        }
        return val;
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stk.isEmpty();
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator obj = new BSTIterator(root);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

参考:https://www.cnblogs.com/grandyang/p/4231455.html

posted on 2018-04-07 14:54  lina2014  阅读(129)  评论(0编辑  收藏  举报

导航