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
相关推荐
LK_0717 分钟前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk55517 分钟前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
Pniubi28 分钟前
力扣21合并两个有序链表
算法·leetcode·职场和发展
用户54817845909501 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
文丑颜不良啊1 小时前
LeetCode3341~3360题目解析
java·leetcode
yiangL_2 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
高洁012 小时前
世界模型的因果内核:从预测表象到理解机制
人工智能·python·深度学习·transformer·迁移学习
数字融合3 小时前
透明化视频动态三维重建空间数据零核心技术
人工智能·python·virtualenv
AI创界者3 小时前
Python 进阶实战(五十四章):大模型推理网关终极架构——分布式全局前缀 Trie 缓存同步与多网关高可用协同调度
人工智能·python·aigc