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
相关推荐
codists4 小时前
《crafting interpreters》阅读笔记:4.6.2
python
2601_967979124 小时前
机器学习必修课:经典算法与Python实战
python·算法·机器学习·实战·课程
cpolar技术支持4 小时前
listen(5) 只排得住 5 个连接:第 6 个客户端卡在 connect 超时,进程活着端口却显示假活不放行
python·socket·tcp·cpolar·故障排查
梯度下降者5 小时前
我校学子斩获 2025 全国高新技术竞赛 Python 赛道全国一等奖
python·教育·竞赛·信息技术·人才培养
小小张说故事5 小时前
Python 的 memoryview 为什么能零拷贝:拆开 buffer protocol、cast 和那道 BufferError
python
Hvitur6 小时前
Java - Lambda
java·开发语言·python
希望我万事顺遂6 小时前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode
2601_967980116 小时前
win10如何把python加入环境变量
python·win10·安装教程·命令行·环境变量
是main不是漫7 小时前
【双指针|LeetCode1089 复写零】巧用逆向思路,破解原地覆盖陷阱
数据结构·算法·leetcode
锋行天下14 小时前
langgraph 后端发自定义数据,前端接收方法概括
人工智能·python