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
相关推荐
XWalnut3 小时前
LeetCode刷题 day4
算法·leetcode·职场和发展
极梦网络无忧3 小时前
OpenClaw 基础使用说明(中文版)
python
codeJinger3 小时前
【Python】操作Excel文件
python·excel
旖-旎4 小时前
分治(库存管理|||)(4)
c++·算法·leetcode·排序算法·快速选择算法
XLYcmy4 小时前
一个针对医疗RAG系统的数据窃取攻击工具
python·网络安全·ai·llm·agent·rag·ai安全
Islucas4 小时前
Claude code入门保姆级教程
python·bash·claude
萝卜白菜。4 小时前
TongWeb7.0相同的类指明加载顺序
开发语言·python·pycharm
赵钰老师4 小时前
【ADCIRC】基于“python+”潮汐、风驱动循环、风暴潮等海洋水动力模拟实践技术应用
python·信息可视化·数据分析
爬山算法5 小时前
MongoDB(80)如何在MongoDB中使用多文档事务?
数据库·python·mongodb