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
相关推荐
树獭非懒2 小时前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习6 小时前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽7 小时前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama
Flittly8 小时前
【从零手写 AI Agent:learn-claude-code 项目实战笔记】(1)The Agent Loop (智能体循环)
python·agent
vivo互联网技术9 小时前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习
敏编程10 小时前
一天一个Python库:virtualenv - 隔离你的Python环境,保持项目整洁
python
喝茶与编码12 小时前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
zone773913 小时前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
用户83562907805113 小时前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python