173. 二叉搜索树迭代器

人盡茶涼 提交于 2020-01-27 06:53:22

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

示例:

BSTIterator iterator = new BSTIterator(root);
iterator.next();    // 返回 3
iterator.next();    // 返回 7
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 9
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 15
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 20
iterator.hasNext(); // 返回 false

 

可以看出本题是中序遍历二叉树的应用。

注意点:正常二叉树结构 、单叉树结构都需要考虑。

考虑实时计算,而不是直接计算出结果然后存储。

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

    private ArrayDeque<Integer> queue = new ArrayDeque(); 

    public BSTIterator(TreeNode root) {
        if(root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack(); 
        TreeNode curr = root;
        while(curr != null || !stack.isEmpty()){
            while(curr != null){
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            queue.add(curr.val);
            curr = curr.right;
        }
    }
    
    /** @return the next smallest number */
    public int next() {
        if(!queue.isEmpty()){
            return queue.pop();
        }
        return 0;
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return queue.size() > 0;
    }
}

/**
 * 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();
 */

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!