题目链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
难度:中等
描述:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
题解
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution:def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:# preorder: [root | left | right]# inorder: [left | root | right]m = {}for idx, i in enumerate(inorder):m[i] = idxdef recursion(p_left, p_right, i_left, i_right):if p_left > p_right:return Nonep_root_idx = p_lefti_root_idx = m[preorder[p_root_idx]]root = TreeNode(val=preorder[p_root_idx])left_size = i_root_idx - i_leftroot.left = recursion(p_left+1, p_left+left_size, i_left, i_root_idx-1)root.right = recursion(p_left+left_size+1, p_right, i_root_idx+1, i_right)return rootreturn recursion(0, len(preorder)-1, 0, len(inorder)-1)
