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
相关推荐
AC赳赳老秦13 分钟前
采集行为合规自检:OpenClaw 自动校验 robots 协议与采集频率,规避违规采集风险
java·开发语言·c++·python·php·deepseek·openclaw
迅猛龙办公室19 分钟前
Python输出当前计算机的系统日期和时间
开发语言·前端·python
XiaoMaqqqq2 小时前
知名的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
言乐62 小时前
Python实现语音审核模型
开发语言·python·django·virtualenv·pygame
程序员清风3 小时前
Python 数据分析环境搭建:从 Jupyter 到 pandas
python·jupyter·数据分析
月光船幽幽3 小时前
加性偏移外推提升参数识别可靠性
python·算法
BD_Marathon4 小时前
消息对象中字段的说明
java·前端·python
Java后端的Ai之路4 小时前
Python进阶探索23 - Python中的Time与Datetime模块
开发语言·数据库·python·datetime·time
Java后端的Ai之路5 小时前
Python进阶探索24_应用案例_linux系统的监控
linux·开发语言·python·应用·探索
happylifetree5 小时前
Python22-26:核心语法-流程控制语句-if条件判断
python