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

中序遍历解决二叉搜索树问题Python3树深度优先搜索通过中序遍历二叉搜索树得到的关键码序列是一个递增序列。这是二叉搜索树的一个重要性质,巧妙利用这一性质可以解决一系列二叉搜索树问题。本系列以以下非递归中序遍历代码为核心,解决一系列相关问题。p = rootst = [] # 用列表模拟实现栈的功能while p is not None or st: whi...
摘要由CSDN通过智能技术生成

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

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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值