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

心路历程:

第一眼看这个题有点懵,后来根据题目给的案例模拟的时候发现,其实只需要在递归函数中每一层构建一个根节点和它的左右子树即可,递归函数传入的是以当前为根节点的前序和中序遍历的数组。

前序遍历用于确认根节点,中序遍历用于确认该根节点的左右子树的长度,然后即可递归不断向下进行。

注意的点:

1、利用递归函数创建二叉树时,每一层new一个node,然后node.left = dfs(...)...,记得最后要把node给return;

2、有return值的递归函数在边界条件和函数上都需要return

3、传参想不明白索引的时候传入数组即可

解法:递归+二叉树建树

python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:

        def dfs(prelist, inlist):  # 构建以prelist[0]为根节点的树
            if not prelist and not inlist: return None
            root = TreeNode(prelist[0])
            root_i = inlist.index(prelist[0])  # 因为值是唯一确定的
            left_len, right_len = root_i, len(inlist) - root_i
            root.left = dfs(prelist[1: 1 +left_len], inlist[:root_i] )
            root.right = dfs(prelist[1+left_len:], inlist[root_i+1:] )
            return root

        return  dfs(preorder, inorder)
相关推荐
z落落1 天前
C#参数区别
java·算法·c#
c238561 天前
vector(下)
数据结构·算法
z落落1 天前
C# 冒泡排序+选择排序 + Array.Sort 自定义排序
数据结构·算法
wyy185100737281 天前
双路并行:一套匹配算法如何解决中文制单的两大核心难题
算法·ai·crm·crm系统
s_w.h1 天前
【 linux 】文件系统
linux·运维·服务器·算法·bash
无限进步_1 天前
【C++】weak_ptr、循环引用与线程安全
开发语言·数据结构·c++·算法·安全
罗超驿1 天前
9.LeetCode 209. 长度最小的子数组 | 滑动窗口专题详解
java·算法·leetcode·面试
水蓝烟雨1 天前
0135. 分发糖果
算法·leetcode
IronMurphy1 天前
【算法五十二】5. 最长回文子串
算法
Lewiis1 天前
白话选择排序
数据结构·算法·排序算法