中序遍历解决二叉搜索树问题

本文介绍了如何利用二叉搜索树的中序遍历性质解决一系列问题,包括实现二叉搜索树迭代器、找到树中的最小绝对差、第k小的元素、众数、范围和以及两数之和IV-输入BST。通过非递归的中序遍历,可以实现这些操作,时间复杂度通常为O(N),空间复杂度在O(log(N))到O(N)之间。

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

中序遍历解决二叉搜索树问题

Python3

深度优先搜索

通过中序遍历二叉搜索树得到的关键码序列是一个递增序列。
这是二叉搜索树的一个重要性质,巧妙利用这一性质可以解决一系列二叉搜索树问题。
本系列以以下非递归中序遍历代码为核心,解决一系列相关问题。

p = root
st = []  # 用列表模拟实现栈的功能
while p is not None or st:
    while p is not None:
        st.append(p)
        p = p.left
    p = st.pop()
    proc(p.val)
    p = p.right

一 二叉搜索树迭代器
(一)算法思路
中序遍历二叉树
(二)算法实现

class BSTIterator:

    def __init__(self, root: TreeNode):
        self.root = root
        self.st = []
        self.current = self.root
        

    def next(self) -> int:
        """
        @return the next smallest number
        """
        while self.current is not None or self.st:
            while self.current is not None:
                self.st.append(self.current)
                self.current = self.current.left
            self.current = self.st.pop()
            node = self.current
            self.current = self.current.right
            return node.val
            
            

    def hasNext(self) -> bool:
        """
        @return whether we have a next smallest number
        """
        return self.current or sel
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值