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
相关推荐
TomEval8 小时前
【测AI】第20篇:大模型安全测试 —— 越狱攻击与防护
人工智能·python·功能测试·ai·aigc·测试用例·安全性测试
RuoyiOffice8 小时前
达梦 DM8 + openGauss:RuoYi Office 的 MySQL 数据转换与导入实践
数据库·spring boot·python·sql·信创
用户0332126663678 小时前
轻松使用 Python 将 RTF 转换为 Word 文档(含批量转换与格式互转)
python
程序猿乐锅8 小时前
面向对象练习:图书借阅系统里的封装、抽象类与多态
开发语言·前端·数据库·后端·python·学习·1024程序员节
xyouyuweizhu8 小时前
Java IO 流详解:流的作用、流的划分与标准输入输出流
java·python·php
lumengabc8 小时前
视频制作文字转语音PPT台词生成合成合并视频导出ffmpeg软件python edge-tts
python
MSTcheng.8 小时前
Agent 跑到一半崩了,怎么从上一步接着跑?LangGraph StateGraph 实战:状态持久化、断点恢复与人工审批
python·状态管理·ai agent·langgraph·断点恢复·人工审批
略略略咯咯8 小时前
33333
开发语言·windows·python
java_prinln8 小时前
11. 说说 Single-Agent 和 Multi-Agent 的设计方案?
python
垆边人似月.8 小时前
第三篇:函数、文件与异常处理 / Functions, Files & Exception Handling
开发语言·python