首页 > 其他 > 详细

173. Binary Search Tree Iterator

时间:2018-10-16 21:44:41      阅读:148      评论:0      收藏:0      [点我收藏+]

一、题目

  1、审题

技术分享图片

 

  2、分析

    给出一棵二分查找树的根节点。实现 next() 方法返回下一个最小的二叉树的节点值。 hasNext() 判断是否还有值。

 

二、解答

  1、思路:

    采用一个 Stack 存储二叉查找树的左斜子树节点值。

    next() 方法返回栈顶节点值,并将其右孩子的左斜子树入栈即可。

    hashNext() 根据栈是否为空即可。

public class BSTIterator {

    private Stack<TreeNode> stack = new Stack<TreeNode>();

    public BSTIterator(TreeNode root) {
        pushAll(root);
    }

    private void pushAll(TreeNode root) {
        while(root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode tmpNode = stack.pop();
        pushAll(tmpNode.right);
        return tmpNode.val;
    }
}

 

173. Binary Search Tree Iterator

原文:https://www.cnblogs.com/skillking/p/9800574.html

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