2015年4月27日星期一

Binary Search Tree Iterator leetcode

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来实现递归的中序遍历。不能递归的都用stack来实现
每个next都相当于返回当前root的子树的最小结点, 所以一直向左找到最小点返回, 下一个点是当前点的右子树(已经没有左子树了)
判定时候的cur!= null是保证判定root点时候

public class BSTIterator {
    private Stack<TreeNode> stack = new Stack<TreeNode>();
    private TreeNode cur;
    public BSTIterator(TreeNode root) {
        cur = root;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return cur != null || !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        TreeNode node = cur;
        cur = node.right;
        return node.val;
    }
}

没有评论:

发表评论