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)
相关推荐
伊玛目的门徒1 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry2 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵3 小时前
【无标题】
数据结构·算法
Kx_Triumphs5 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎5 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀6 小时前
约瑟夫环问题
算法
科技大视界8 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴8 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe8 小时前
算法滑动窗口
数据结构·算法