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
相关推荐
yangshicong10 分钟前
第11章:结构化输出与数据提取 —— 让 AI 直接返回你想要的数据格式
数据库·人工智能·redis·python·langchain·ai编程
言之。23 分钟前
【Python】免费的中文 AI 配音方案
开发语言·人工智能·python
Warson_L25 分钟前
python dict key详解
python
天天进步201540 分钟前
Python全栈项目:从零手操一个高性能 API 网关
开发语言·python
安生生申2 小时前
使用pygame实现2048
开发语言·python·pygame
徐图图不糊涂3 小时前
搭建简易版的Rag系统
python·pycharm
灰灰勇闯IT3 小时前
pyasc:用 Python 调用 CANN 的推理能力
开发语言·python
明月_清风3 小时前
FastAPI 从入门到实战:3 分钟构建高性能异步 API
后端·python·fastapi
bellus-4 小时前
ubuntu26测试win10的ollama大模型性能
python
水木流年追梦4 小时前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式