首页 > 其他 > 详细

[LeetCode]Binary Search Tree Iterator

时间:2018-01-28 12:25:32      阅读:219      评论:0      收藏:0      [点我收藏+]

可以把中序遍历的过程融入到next函数中,可以更快,下边的做法是先遍历完,比较垃圾

//记录节点值
    Queue<Integer> vals = new LinkedList<>();
    public BSTIterator(TreeNode root) {
        //构造函数不能主动调用所以不能递归,迭代中序遍历得到升序list
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty()||root!=null)
        {
            if (root!=null)
            {
                stack.push(root);
                root = root.left;
            }
            else
            {
                root = stack.pop();
                vals.offer(root.val);
                root = root.right;
            }
        }
    }

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

    /** @return the next smallest number */
    public int next() {
        return vals.poll();
    }

 

[LeetCode]Binary Search Tree Iterator

原文:https://www.cnblogs.com/stAr-1/p/8370649.html

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