Python | Leetcode Python题解之第105题从前序与中序遍历序列构造二叉树

题目:

题解:

python 复制代码
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if not preorder:
            return None

        root = TreeNode(preorder[0])
        stack = [root]
        inorderIndex = 0
        for i in range(1, len(preorder)):
            preorderVal = preorder[i]
            node = stack[-1]
            if node.val != inorder[inorderIndex]:
                node.left = TreeNode(preorderVal)
                stack.append(node.left)
            else:
                while stack and stack[-1].val == inorder[inorderIndex]:
                    node = stack.pop()
                    inorderIndex += 1
                node.right = TreeNode(preorderVal)
                stack.append(node.right)

        return root
相关推荐
英英_3 分钟前
视频爬虫的Python库
开发语言·python·音视频
猛犸MAMMOTH8 分钟前
Python打卡第46天
开发语言·python·机器学习
枫景Maple22 分钟前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
多多*34 分钟前
微服务网关SpringCloudGateway+SaToken鉴权
linux·开发语言·redis·python·sql·log4j·bootstrap
梓仁沐白34 分钟前
【Kotlin】协程
开发语言·python·kotlin
Java Fans1 小时前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
豌豆花下猫1 小时前
Python 潮流周刊#105:Dify突破10万星、2025全栈开发的最佳实践
后端·python·ai
嘻嘻哈哈OK啦1 小时前
day46打卡
python
木头左1 小时前
Docker容器化技术概述与实践
python
坚持就完事了2 小时前
大二下期末
python·numpy·pandas