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
相关推荐
洛水水16 分钟前
【力扣100题】76.搜索插入位置
数据结构·算法·leetcode
c_lb728822 分钟前
期货量化策略从 Windows 迁到 Linux 服务器:环境注意点
linux·服务器·windows·python
北凉军26 分钟前
更换PyCharm 任务栏图标
ide·python·pycharm
yijianace31 分钟前
Python爬虫实战:BooksToScrape 多线程爬取与图片下载
开发语言·爬虫·python
LadenKiller31 分钟前
期货多品种轮动标的池:天勤 query_quotes 筛品种写法
python·区块链
郑洁文32 分钟前
基于Python+回归分析的电子产品需求数据分析与预测
python·数据分析·回归·电子产品需求数据·电子产品数据分析
IT策士38 分钟前
Redis 从入门到精通:Python 操作 Redis 进阶
数据库·redis·python
质造者43 分钟前
Python 本地 RAG 实战 | Ollama+ChromaDB 实现 PDF 离线智能问答
开发语言·python·pdf·大模型·rag
骑士雄师43 分钟前
18.1 星系案例:多智能体宇宙探索系统(学习langgraph 的存储知识)
windows·python·学习
wabs6661 小时前
关于动态规划【力扣343.整数拆分的递推公式怎么理解?】
算法·leetcode·动态规划