leetcode-105. 从前序与中序遍历序列构造二叉树

题目描述

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

示例 1:

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

示例 2:

复制代码
输入: preorder = [-1], inorder = [-1]
输出: [-1]

思路

剑指offer重建二叉树-CSDN博客

1)递归地按照前序的顺序,制作成根节点

2)在中序中找到根节点的索引,按照其索引将树分为左子树和右子树

3)直到前序和中序序列没有

4)返回根节点

python 复制代码
# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if not preorder or not inorder:
            return None
        root = TreeNode(preorder[0])
        index = inorder.index(root.val)
        root.left = self.buildTree(preorder[1:index+1],inorder[:index])
        root.right = self.buildTree(preorder[index+1:],inorder[index+1:])
        return root

def printTreeMidOrder(root, res):
    if not root:
        return None
    if root.left:
        printTreeMidOrder(root.left, res)
    res.append(root.val)
    if root.right:
        printTreeMidOrder(root.right, res)

if __name__ == '__main__':
    s = Solution()
    pre = [1, 2, 4, 7, 3, 5, 6, 8]
    tin = [4, 7, 2, 1, 5, 3, 8, 6]
    root = s.buildTree(pre, tin)
    # 打印中序遍历结果
    res = []
    printTreeMidOrder(root, res)
    print(res)
相关推荐
历程里程碑4 小时前
普通数组-----除了自身以外数组的乘积
大数据·javascript·python·算法·elasticsearch·搜索引擎·flask
AI视觉网奇4 小时前
blender 导入fbx 黑色骨骼
学习·算法·ue5·blender
weixin_468466855 小时前
目标识别精度指标与IoU及置信度关系辨析
人工智能·深度学习·算法·yolo·图像识别·目标识别·调参
多恩Stone5 小时前
【3D AICG 系列-8】PartUV 流程图详解
人工智能·算法·3d·aigc·流程图
铸人5 小时前
再论自然数全加和-质数的规律
数学·算法·数论·复数
历程里程碑6 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
YGGP7 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
你撅嘴真丑13 小时前
第九章-数字三角形
算法
uesowys13 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder13 小时前
hot100-二叉树I
数据结构·python·算法·二叉树