leetcode 173. Binary Search Tree Iterator-二叉搜索树迭代|中序遍历

本文介绍了一种利用中序遍历实现二叉搜索树迭代器的方法,通过两种不同的实现方式,一种使用栈来实现中序遍历,另一种则通过巧妙地调整指针指向来达到相同的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:173. Binary Search Tree Iterator

【思路-Java】中序遍历非递归实现

我们知道二叉搜索树当前节点值总是大于左子树上的任一节点值,总是大于右子树上的任一节点值。要从小到大取出该节点,我们可以采用二叉树的中序遍历,该思路借用一个栈来实现,如果对二叉树的中序遍历思路不是很清晰的,可以参考我的另一篇博文:leetcode 94. Binary Tree Inorder Traversal-中序遍历|递归|非递归

public class BSTIterator {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    public BSTIterator(TreeNode root) {
        while(root != null) {
            stack.add(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 temp = stack.pop();
        int val = temp.val;
        if(temp.right != null) {
            temp = temp.right;
            while (temp != null) {
                stack.add(temp);
                temp = temp.left;
            }
        }
        return val;
    }
}
61 / 61  test cases passed. Runtime: 6 ms  Your runtime beats 78.97% of javasubmissions.


【思路2-Java】
如果我们打破常规,不用栈来实现,那么我们就需要变换策略,需要申请几枚指针:


该思路就是借助指针,逐一将最左端的点加到 root 指针的右边

public class BSTIterator {
    TreeNode root = new TreeNode(0);
    public BSTIterator(TreeNode root) {
        this.root.right = root;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return root.right != null;
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode next = root.right;
        if (next.left == null) {
            root = next;
            return next.val;
        }
        TreeNode right = root.right;
        TreeNode parent = root;
        while(next.left != null) {
            parent = next;
            next = next.left;
        }
        parent.left = next.right;
        root.right = next;
        next.right = right;
        root = root.right;
        return root.val;
    }
}
61 / 61  test cases passed. Runtime: 5 ms  Your runtime beats 94.32% of javasubmissions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值