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)
相关推荐
Wilber的技术分享8 分钟前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病11 分钟前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中1 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy2 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209252 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
靴子学长2 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv
寒秋花开曾相惜2 小时前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
Гений.大天才2 小时前
2026年计算机领域的年度主题与范式转移
算法
njidf3 小时前
C++与Qt图形开发
开发语言·c++·算法
ZoeJoy83 小时前
算法筑基(一):排序算法——从冒泡到快排,一文掌握最经典的排序算法
数据结构·算法·排序算法