[LeetCode]Binary Search Tree Iterator

来源:互联网 发布:手机改图软件 编辑:程序博客网 时间:2024/06/05 09:13

Question

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.


本题难度Medium。

题意

设计一个迭代器类,该类可以以Avg O(1)的时间枚举二叉查找树的最小值,且仅使用
O(h)空间(难点在此)

复杂度

时间 O(1) 空间 O(h)

Example

   10 /    \1      11 \       \   6      12

思路

建立一个堆栈,先将最左边的结点从大到小压入栈,这样的话,为了实现迭代即返回下一个node的next()函数就要考虑右边的结点。比如Example中的BST,stack第一次pop出来的结点是1,然后就应该把它的右子树结点6压入stack;又如pop出了root结点10以后,就要把11压入堆栈,这样,在pop出11之后,再将12压入堆栈。如此,实现next()函数。

代码

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

参考

[LintCode] Binary Search Tree Iterator

0 0
原创粉丝点击