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

[LC] 173. Binary Search Tree Iterator

时间:2020-01-15 23:18:13      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:number   ram   whether   tree   style   arch   cal   empty   led   


Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class BSTIterator {
    private LinkedList<TreeNode> stack;
    private TreeNode cur;
    public BSTIterator(TreeNode root) {
        stack = new LinkedList<>();
        cur = root;
    }
    
    /** @return the next smallest number */
    public int next() {
        while (cur != null) {
            stack.offerFirst(cur);
            cur = cur.left;
        }
        cur = stack.pollFirst();
        int val = cur.val;
        cur = cur.right;
        return val;
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty() || cur != null;
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator obj = new BSTIterator(root);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

[LC] 173. Binary Search Tree Iterator

标签:number   ram   whether   tree   style   arch   cal   empty   led   

原文地址:https://www.cnblogs.com/xuanlu/p/12199077.html

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