【leetcode100】从前序与中序遍历序列构造二叉树

1、题目描述

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

示例 1:

复制代码
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]

2、初始思路

2.1 思路

前序遍历中第一个节点为根节点,根据根节点可以在中序遍历中分辨出来左子树和右子树的节点,然后按照相同的方法,可以构建左子树和右子树的子树。

复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        #方便查找根节点的位置
        dic = {}
        for i in range(len(inorder)):
            dic[inorder[i]] = i
        def tree(root,left,right):
            if left > right:
                return
            #节点在前序遍历中的位置索引
            i = dic[preorder[root]]
            node = TreeNode(preorder[root])
            #见图
            node.left = tree(root+1,left,i-1)
            node.right = tree(i-left+root+1,i+1,right)
            return node
        return tree(0,0,len(preorder)-1)

以下为node.left = tree(root+1,left,i-1),node.right = tree(i-left+root+1,i+1,right)的图解。

相关推荐
跟橙姐学代码38 分钟前
手把手教你玩转 multiprocessing,让程序跑得飞起
前端·python·ipython
LCS-3121 小时前
Python爬虫实战: 爬虫常用到的技术及方案详解
开发语言·爬虫·python
穷儒公羊1 小时前
第二章 设计模式故事会之策略模式:魔王城里的勇者传说
python·程序人生·设计模式·面试·跳槽·策略模式·设计规范
心本无晴.1 小时前
面向过程与面向对象
python
花妖大人1 小时前
Python用法记录
python·sqlite
站大爷IP1 小时前
用PyQt快速搭建桌面应用:从零到实战的实用指南
python
站大爷IP2 小时前
PyCharm:Python开发者的智慧工作台全解析
python
zhanghongyi_cpp2 小时前
linux的conda配置与应用阶段的简单指令备注
linux·python·conda
MThinker2 小时前
14.examples\01-Micropython-Basics\demo_yield.py 加强版
python·学习·智能硬件·micropython·canmv·k230
LiRuiJie2 小时前
基于LangChain + Milvus 实现RAG
python·langchain·milvus·rag