Binary Search Tree Iterator

题目地址:
https://leetcode.com/problems/binary-search-tree-iterator/#/description

题目:
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.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

解题思路:
这道题可以用一个stack,然后一直往左子树走到底。

代码:



public class BSTIterator {

    Stack<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        stack = new Stack<>();
        TreeNode next = root;
        if(next != null){
            stack.push(next);
            while(next.left != null){
                stack.push(next.left);
                next = next.left;
            }
        }
    }

    public boolean hasNext() {
        return !stack.isEmpty();
    }

    public int next() {
        TreeNode curr = stack.pop();
        TreeNode next = curr;
        if(next.right != null){
            next = next.right;
            stack.push(next);
            while(next.left != null){
                stack.push(next.left);
                next = next.left;
            }
        }
        return curr.val;
    }

}

Comments

Popular Posts