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 小时前
角谷猜想的任意算法测试
数据结构·人工智能·算法
happygrilclh4 小时前
赚外快了:等离子表面处理机电源算法需求说明
算法
ji198594435 小时前
MATLAB 求散点曲线斜率
开发语言·算法·matlab
kaikaile19955 小时前
MATLAB 实现:Koch & Zhao 图像水印算法(DCT域)
开发语言·算法·matlab
QiLinkOS5 小时前
QiLink开源生态的三维重构:基于时间、空间与社会价值的底层规则创新白皮书
大数据·c++·人工智能·科技·算法·gitee·开源
牛肉在哪里5 小时前
ros2 从零开始28 监听广播C++
开发语言·c++·算法·机器人
乐观勇敢坚强的老彭5 小时前
GESP一级核心算法:循环与条件判断的结合
java·数据结构·算法
noipp5 小时前
推荐题目:洛谷 P1737 [NOI2016] 旷野大计算
linux·数据结构·算法
QiLinkOS5 小时前
极客精神与商业思维的融合实践(2)
c语言·c++·人工智能·算法·开源协议
code_pgf6 小时前
改进模型架构来减少MLLMs中的幻觉现象
人工智能·深度学习·算法