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
相关推荐
退休倒计时9 分钟前
【每日五题】leetcode TypeScript
算法·leetcode·职场和发展·typescript
weixin_4407305027 分钟前
allure总结--解决版本不相容,没有trend(生成原始报告+复制history后在一起生成新报告)+jenkins集成
python·测试报告·allure
小柯南敲键盘28 分钟前
跨马翻译:图片翻译软件批量处理,跨境电商视频字幕AI智能抠图
人工智能·python·音视频
BYSJMG28 分钟前
计算机毕业设计选题推荐|【基于大数据的植被光谱特征与环境因子关联分析及可视化】Spark+K-Means
大数据·python·信息可视化·数据分析·spark·kmeans·课程设计
茶栀(*´I`*)34 分钟前
Python网络机器人入门:从Robots协议、网页结构到Requests库的基础实践
网络·python·机器人
SunnyDays101141 分钟前
如何使用 Python 添加和编辑 Excel VBA 宏(无需安装 Excel)
开发语言·python·excel·vba
2601_9622959942 分钟前
Python+Appium 自动化测试:从基础语法到 PO 模式设计,构建稳定测试框架
自动化测试·python·appium·测试框架·po模式
开源量化GO42 分钟前
先确认策略想法能不能变成规则
人工智能·python
拜托多多指教43 分钟前
【Pytest框架学习】分层架构
python·pytest
心抵鹊44 分钟前
力扣每日一题:计算右侧小于当前元素的个数(hard)
算法·leetcode