美文网首页Leetcode每日两题程序员
Leetcode 173. Binary Search Tree

Leetcode 173. Binary Search Tree

作者: ShutLove | 来源:发表于2017-11-13 22:43 被阅读7次

    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.

    思路:BST的中序遍历就是一个升序,满足题目的迭代要求。考虑到要O(h)的空间复杂度,用栈可以保存当前最小node的父节点,每次最小值在栈顶,O(1)的时间复杂度。

    public class BSTIterator {
    
    Stack<TreeNode> stack = new Stack<>();
    
    public BSTIterator(TreeNode root) {
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }
    
    /** @return the next smallest number */
    public int next() {
        TreeNode node = stack.pop();
        TreeNode dummy = node.right;
        while (dummy != null) {
            stack.push(dummy);
            dummy = dummy.left;
        }
        return node.val;
    }
    }

    相关文章

      网友评论

        本文标题:Leetcode 173. Binary Search Tree

        本文链接:https://www.haomeiwen.com/subject/ljvtvxtx.html