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
相关推荐
Python+9935 分钟前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
G.O.G.O.G1 小时前
LeetCode SQL 从入门到精通(MySQL)06(上)
数据库·sql·mysql·leetcode
dunge20261 小时前
2026年7月最新ChatGPT Plus / Pro 与 Codex:当 AI Agent 最新5.6版本来袭,必须理解事务、幂等与补偿
开发语言·人工智能·python
闪电悠米3 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
小白学大数据3 小时前
两周完成爬虫技术栈升级:Scrapy 迁移 Crawlo 的路径与取舍
爬虫·python·scrapy
用户8356290780513 小时前
使用 Python 在 Excel 中添加和自定义文本框
后端·python
总裁余(余登武)4 小时前
python多个py文件打包【解决exe不能移动运行bug】
python
卡提西亚4 小时前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结4 小时前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
kisloy4 小时前
【python零基础教程第24讲】代码规范与质量管控
开发语言·python