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

[LeetCode]Binary Search Tree Iterator

时间:2018-01-28 12:50:17      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:nod   treenode   ret   迭代   etc   iterator   pre   递归   sea   

可以把中序遍历的过程融入到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

标签:nod   treenode   ret   迭代   etc   iterator   pre   递归   sea   

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

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