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
相关推荐
极光代码工作室28 分钟前
基于深度学习的手写数字识别系统
人工智能·python·深度学习·神经网络·机器学习
geovindu33 分钟前
python: speech to text offline
开发语言·python·语音识别
AI创界者44 分钟前
告别云端限制!Sulphur 2 本地文生视频/图生视频整合包,本地部署,解压即用,保姆级部署与工作流实战
人工智能·python·aigc·音视频
tsfy20031 小时前
Python批量调整Excel格式,并排版导出PDF
python·pdf·excel
木囧1 小时前
PyCharm手动创建虚拟环境
ide·python·pycharm
李可以量化1 小时前
QMT 量化实践:两种方式获取个股上市日期(内置 Python + 原生 Python 完整可运行代码)
python
是多巴胺不是尼古丁2 小时前
期末java复习--string
java·开发语言·python
garmin Chen2 小时前
从 Transformer 到 Agent:大模型技术全景解析
java·人工智能·python·深度学习·transformer
没有钱的钱仔2 小时前
pytorch_cuda安装
人工智能·pytorch·python
Full Stack Developme2 小时前
Apache Tika 教程
java·开发语言·python·apache