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
相关推荐
郝学胜_神的一滴1 分钟前
Effective Python 条款 8: 同时遍历多组序列:zip 与 zip_longest 的实战避坑指南
python·pycharm
承渊政道11 分钟前
【Python编程—从入门到实践】(Python字典:从基础语义到现代工程实践)
开发语言·python·pycharm·字典·嵌套
麻雀飞吧13 分钟前
搜索“近期量化入门”时,先补交易理解再看 Python 和 API
人工智能·python
名字还没想好☜1 小时前
Python 字符编码实战:encode/decode、UnicodeDecodeError 与 open 的 encoding 坑
开发语言·后端·python·编程语言
带多刺的玫瑰1 小时前
Leecode#29刷题之两数相除
java·python·算法
smj2302_796826521 小时前
解决leetcode第4017题数组中的峰值II
python·算法·leetcode
午彦琳1 小时前
2026.9.9
数据结构·算法·leetcode
卷无止境1 小时前
AI Agent编程中,重构节奏与安全检查的门道
后端·python
慧都小妮子1 小时前
用 Python 批量把 PDF 参考文献排成 MLA 格式:Spire.Doc for Python 实战
python·pdf·c#·spire.doc·mla格式·参考文献排版·pdf批量处理
卷无止境1 小时前
AI编程时代,代码复杂性正在悄悄失控
后端·python