输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
前序: 跟节点 左节点 右节点
中序: 左节点 跟节点 右节点
# 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:
self.preorder = preorder
self.dic = {}
length = len(inorder)
for i in range(length):
# 储存index
self.dic[inorder[i]] = i
return self.recur(0, 0, length - 1)
def recur(self, pre_root, in_left, in_right):
if in_left > in_right:
return
# 在中序遍历中发现根节点的index
idx = self.dic[self.preorder[pre_root]]
root = TreeNode(self.preorder[pre_root])
root.left = self.recur(pre_root + 1,in_left, idx - 1)
root.right = self.recur(idx - in_left + pre_root + 1, idx + 1, in_right)
# 右节点 = 跟节点 + 左子树长度
return root