首页 > 其他 > 详细

leetcode 173. Binary Search Tree Iterator

时间:2019-08-18 11:18:51      阅读:99      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

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

 

leetcode 173. Binary Search Tree Iterator

原文:https://www.cnblogs.com/hwd9654/p/11371416.html

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