leetcode 173. Binary Search Tree Iterator

 

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();
    }
}

 

posted @ 2019-08-18 09:03  南山南北秋悲  阅读(75)  评论(0编辑  收藏  举报