LeetCode - 173. Binary Search Tree Iterator

要求实现Binary Search Tree的hasNext()和next()操作,最小的元素自然是从root开始一直找左子树左子树直到为空,这是我们找到了我们需要的第一个元素,但是接下来的元素怎么办呢?Binary Search Tree又没有回退的指针,就没办法了,这样是不行的,所以我们必然要采取某种方法记录一路寻找下来的路径上的元素,这里我们采用了Stack,它具有后进先出的功能,符合我们逻辑上的要求。

使用了Stack之后,我们可以把从root到最小元素的一路的左子树元素存储到stack里面,对于next()函数,我们第一步需要做的就是把栈顶的元素pop出来,这就是我们需要找的元素,同时我们还要修改指针,使得指针指向下一个需要pop的元素。这里我们遇到了一个问题,如果当前元素的右子树不为空,那么下一个元素就是它右子树中左子树左子树....的最小元素,同样地我们也需要在down to leaf的过程中,把一路上的元素加入到Stack中。因为根据Binary Search Tree的性质,某个结点的右子树中的所有元素都是小于当前结点的父节点的元素的。

而对于hasNext()函数,我们只要检查Stack是否为空就行。整个代码如下:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

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

    public BSTIterator(TreeNode root) {
        pushAll(root);
    }

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

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

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值