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
相关推荐
fanruitian3 分钟前
python 机器学习 ML LinearRegression KNN KMeans
python·机器学习·kmeans
鱼宵9 分钟前
取集合第一个元素,Java 为什么要写三种写法?
java·windows·python·java21
卷无止境18 分钟前
给AI装上一双眼睛:快速构建代码验证器的思路与落地方案
后端·python
维克兜率天37 分钟前
【维克】指数调整:哪些股票会被“强制买入“?
人工智能·python·算法
come112341 小时前
Codex 下不同场景 模式选择
python
神也畏惧菠萝1 小时前
Day08 Python流程控制从入门到上瘾:if/match/while/for四件套,从B站登录一路打到猜数字游戏
python·算法·数据存储·for·while·if·ifelse
言乐62 小时前
通过 3D 动画直观演示球形瓶内可滑动半圆机构在倾倒时防粘盖、回正时刮膏体的运动学过程
python·3d·django·virtualenv·pygame
quantdash_cc2 小时前
ETF 行情数据清洗实战:字段语义拆解、标的池整理与五个校验清单
python·数据分析·pandas·量化交易·股票数据·quantdash
小熊恋旧2 小时前
Python 面向对象编程:方法、属性、继承与多态详解
开发语言·python
威哥爱编程3 小时前
Python 智能体开发实战 05:一问教材内容它就编?先把答案从你自己的资料里检索出来
python·agent