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)
相关推荐
Once_day28 分钟前
代码训练LeetCode(34)文本左右对齐
算法·leetcode·c
zhuiQiuMX39 分钟前
SQL力扣
数据库·sql·leetcode
tony36542 分钟前
强化学习 A2C算法
人工智能·算法
Tess_Blingbling1 小时前
力扣Hoot100 第一天 | 哈希3题
leetcode·哈希算法·散列表
好易学·数据结构1 小时前
可视化图解算法51:寻找第K大(数组中的第K个最大的元素)
数据结构·python·算法·leetcode·力扣·牛客网·堆栈
电院工程师1 小时前
轻量级密码算法PRESENT的C语言实现(无第三方库)
c语言·算法·安全·密码学
bubiyoushang8882 小时前
MATLAB实现图像纹理特征提取
人工智能·算法·matlab
了不起的杰2 小时前
[算法][好题分享][第三大的数][最短无序子数组]
算法
a东方青2 小时前
[蓝桥杯 2023 国 B] AB 路线 (BFS)
c++·算法·职场和发展·蓝桥杯·宽度优先
依然易冷3 小时前
【LLM Tool Learning】论文分享: Chain-of-Tools
算法