题目链接: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 = None
class 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] = idx
def recursion(p_left, p_right, i_left, i_right):
if p_left > p_right:
return None
p_root_idx = p_left
i_root_idx = m[preorder[p_root_idx]]
root = TreeNode(val=preorder[p_root_idx])
left_size = i_root_idx - i_left
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 root
return recursion(0, len(preorder)-1, 0, len(inorder)-1)