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
相关推荐
NetX行者1 分钟前
Python 工程化入门:从脚本到规范的 Python 项目结构
网络·python
MasonYyp13 分钟前
asyncio并发协程
python
小小张说故事32 分钟前
Python 的整数为什么永远不会溢出?拆开大整数对象,看 30 位一节的存储与运算代价
python
Nil2081 小时前
leetcode 49字母异位分组
算法·leetcode·哈希算法
用户298698530141 小时前
Python 实现 Word 与 TIFF 双向转换的方案
后端·python·api
benchmark_cc1 小时前
实时行情和分钟 K 线应该如何配合使用?从信号计算到交易决策的完整分析
大数据·python·数据分析·pandas·量化交易·股票数据·quantdash
LMT流氓兔1 小时前
第四单元——第17课:让回答边生成、边显示
服务器·数据库·人工智能·python·oracle·langchain
MetWeave1 小时前
从零跑一个气象数据管道:抓取、清洗、对账、节奏
后端·python
用户3851408539471 小时前
Python 的 O_NOFOLLOW 为什么挡不住中间目录的符号链接?
python
Generalzy2 小时前
Qt 桌面开发入门:PySide6 学习路线、架构原理与技术选型
笔记·python·学习