题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
难度:中等
描述:
给定两个整数数组 preorder 和 inorder,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
提示:preorder和inorder中无重复元素。
题解
preorder中的第一个值是根节点root,找到root在inorder中的位置就可以找到root左子树和右子树的大小。那么就可以找到root左子树和右子树在preorder中的分布。
| root | left_subtree | right_subtree |
|---|---|---|
| left_subtree | root | right_subtree |
|---|---|---|
# 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 = rightclass Solution:def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:def recursion(p_left, p_right, i_left, i_right):if p_left > p_right:return Nonep_root_idx = p_lefti_root_idx = hm[preorder[p_root_idx]]left_size = i_root_idx - i_leftroot = TreeNode(val=preorder[p_root_idx])root.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 rootlength = len(preorder)hm = {}for i in range(length):hm[inorder[i]] = ireturn recursion(0, length-1, 0, length-1)
