二叉查找树迭代器

描述

设计实现一个带有下列属性的二叉查找树的迭代器:
next()返回BST中下一个最小的元素

元素按照递增的顺序被访问(比如中序遍历)
next()和hasNext()的询问操作要求均摊时间复杂度是O(1)O(1)

样例

样例 1:

输入:

tree = {10,1,11,#,6,#,12}

输出:

[1,6,10,11,12]

解释:

二叉查找树如下 :
  10
/       \
1     11
  \       \
  6       12
可以返回二叉查找树的中序遍历 [1,6,10,11,12]

实现要点

递归 → 非递归,意味着自己需要控制原来由操作系统控制的栈的进进出出如何找到最小的第一个点?最左边的点即是。
如何求出一个二叉树节点在中序遍历中的下一个节点?
在 stack 中记录从根节点到当前节点的整条路径,下一个点=右子树最小点 or 路径中最近一个通过左子树包含当前点的点
在这里插入图片描述

代码

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 * Example of iterate a tree:
 * BSTIterator iterator = new BSTIterator(root);
 * while (iterator.hasNext()) {
 *    TreeNode node = iterator.next();
 *    do something for node
 * } 
 */public class BSTIterator {
    /**
    * @param root: The root of binary tree.
    */
    private Stack<TreeNode> stack = new Stack<>();

    public BSTIterator(TreeNode root) {
        // do intialization if necessary
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    /**
     * @return: True if there has next node, or false
     */
    public boolean hasNext() {
        // write your code here
        return !stack.isEmpty();
    }

    /**
     * @return: return next node
     */
    public TreeNode next() {
        TreeNode curt = stack.peek();
        TreeNode node = curt;

        if (node.right == null) {
            node = stack.pop();
            //下一个点=右子树最小点 or 路径中最近一个通过左子树包含当前点的点
            while (!stack.isEmpty() && stack.peek().right == node) {
                node = stack.pop();
            }
        }else {
            node = node.right;
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
        }
        return curt;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芝士汉堡 ིྀིྀ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值