Binary Search Tree Iterator

https://oj.leetcode.com/problems/binary-search-tree-iterator/

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.

    public BSTIterator(TreeNode root) {
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
    }

    /** @return the next smallest number */
    public int next() {
    }

从小到大的顺序输出一个Bst,可行的做法就是in-order traversal。可是一般递归的in order traversal是做不到iterator的效果的,只有循环iteration的in order traversal才可以。结合 Binary Tree Preorder Traversal 提到的循环递归树的做法,首先我们给出一个in-order traversal 循环的代码

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<Integer>();
        Stack<TreeNode> tree_stack = new Stack<TreeNode>();
        TreeNode tmp = root;
        while(tmp != null || !tree_stack.isEmpty()){
            if(tmp != null){
                tree_stack.push(tmp);
                tmp = tmp.left;
            }else{
                tmp = tree_stack.pop();
<pre name="code" class="java">                res.add(tmp.val);
  tmp = tmp.right; } } return res; }

 跟preorder不同的就是把输出的位置从if放到else里了。 

根据这一段代码,其实这个iterator就很好写了。给出代码如下:

    Stack<TreeNode> dfs_stack;
    TreeNode cur;
    public BSTIterator(TreeNode root) {
        dfs_stack = new Stack<TreeNode>();
        cur = root;
    }

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

    /** @return the next smallest number */
    public int next() {
        int res = 0;
        while(cur != null || !dfs_stack.isEmpty()){
            if(cur != null){
                dfs_stack.add(cur);
                cur = cur.left;
            }else{
                cur = dfs_stack.pop();
                res = cur.val;
                cur = cur.right;
                break;
            }
        }
        return res;
    }

顺便说一下,如果这个是要求Preorder的iterator的话,hasNext的条件就需要做一下调整。因为这个时候即使dfs_stack非空,但实际上还是有可能已经遍历完了。最后栈里面可能都是要往上循环的parent节点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值