LeetCode 173: Binary Search Tree Iterator

/**
 * 173. Binary Search Tree Iterator
 * 1. Time:O()  Space:O()
 * 2. Time:O()  Space:O()
 */

// 1. Time:O()  Space:O()
class BSTIterator {

    ArrayList<Integer> res;
    int index;
    
    public BSTIterator(TreeNode root) {
        this.res = new ArrayList<>();
        this.index = -1;
        this.inOrder(root);
    }
    
    private void inOrder(TreeNode root){
        if(root==null) return;
        inOrder(root.left);
        res.add(root.val);
        inOrder(root.right);
    }
    
    /** @return the next smallest number */
    public int next() {
        return this.res.get(++index);
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return this.index+1<this.res.size();
    }
}

// 2. Time:O()  Space:O()
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 node = stack.pop();
        TreeNode tmp = node.right;
        while(tmp!=null){
            stack.push(tmp);
            tmp = tmp.left;
        }
        return node.val;
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }
}
posted @ 2020-04-28 13:58  AAAmsl  阅读(66)  评论(0编辑  收藏  举报