剑指 Offer 07. 重建二叉树
Difficulty: 中等
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/
9 20
/
15 7
限制:
0 <= 节点个数 <= 5000
注意:本题与主站 105 题重复:
Solution
本题与主站 105 题重复:LeetCode 105. 从前序与中序遍历序列构造二叉树 - swordspoet - 博客园
# 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:
def helper(pre_left, pre_right, in_left, in_right):
if pre_left> pre_right:
return None
pre_root = pre_left
in_root = index[preorder[pre_root]]
root = TreeNode(preorder[pre_root])
left_subtree_size = in_root - in_left
root.left = helper(pre_left+1, pre_left+left_subtree_size, in_left, in_root-1) # 前序遍历的第二个元素开始!
root.right = helper(pre_left+1+left_subtree_size, pre_right, in_root+1, in_right)
return root
n = len(preorder)
index = {e:i for i,e in enumerate(inorder)}
return helper(0, n-1, 0, n-1)