Binary Search Tree Iterator

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

解题思路:

首先回顾一下二叉查找树:

二叉查找树(BST)是指一棵空树或者是具有以下性质的树:

  • 任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
  • 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
  • 任意节点的左、右子树也分别为二叉查找树;
  • 没有键值相等的节点。

这里要求我们设计一个 BST 的迭代器,意思是将 BST 中的元素有小到大的输出出来。
例,这里是一棵 BST:
图片来自 program creek

调用如下代码:

BSTIterator i = new BSTIterator(root);
while (i.hasNext()) {
    i.next();
}

输出结果为:[1, 3, 4, 6, 7, 8, 10, 13, 14]

最主要是 next 方法的设计,这里采用栈,根据 BST 的特点:左子树上的所有节点均小于根结点,右子树的所有节点均大于根节点。所以相当于是一次中序遍历。

我们先将所有左节点入栈,直到左子树为空。接着挨个弹出左节点,如果判断到它具有右节点,将右节点作为根节点再次将它的左节点入栈。

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

public class BSTIterator {

    Stack<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>();
        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();
        int result = node.val;
        if (node.right != null) {
            node = node.right;
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
        }
        return result;
    }
}

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值