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

leetcode 173. Binary Search Tree Iterator

时间:2019-08-18 10:14:16      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:etc   search   tac   ber   tree   style   tco   while   whether   

技术图片

 

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

标签:etc   search   tac   ber   tree   style   tco   while   whether   

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

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