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
相关推荐
kobe_OKOK_2 小时前
DRF接口幂等操作
python·django
廿士3 小时前
python脚本使用相关
python
青 春 记 忆3 小时前
零基础入门python19:Flask账本第一步——应用工厂、蓝图和健康检查
python·flask·后端开发
朦胧之3 小时前
Python 后端核心知识
python
denggun123454 小时前
yield
前端·数据库·python
zx_741484815 小时前
【Python 入门】面向对象基础:类、对象、成员变量与构造方法
开发语言·python
招财小梗5 小时前
沈阳商贸公司AI企业服务优势几何?
大数据·人工智能·python
ZISHU_9876 小时前
用 TLabel 给 SynTouch BioTac 数据做语义标注:从原始信号到结构化标注
开发语言·人工智能·python·数据·机器人触觉
m0_617493947 小时前
SSLError [ASN1: NOT_ENOUGH_DATA] 问题排查与解决指南
python·ssl
whcyhhh7 小时前
头歌实践教学平台:数据科学与大数据技术导论(七上)
大数据·数据库·python