题解 | #重建二叉树#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
#递归方法
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pre int整型一维数组
# @param vin int整型一维数组
# @return TreeNode类
#
class Solution:
def reConstructBinaryTree(self , pre: List[int], vin: List[int]) -> TreeNode:
if pre == []:
return None
#设定根节点
root = TreeNode(pre[0])
#找到根节点在中序对应的索引,对应出左子树和右子树
in_index = vin.index(root.val)
in_left = vin[:in_index]
#根据左右子树序列长度,确定先序序列中的左子树和右子树
len_left = len(in_left)
in_right = vin[in_index+1:]
pre_left = pre[1:len_left+1]
pre_right = pre[len_left+1:]
root.left = self.reConstructBinaryTree(pre_left, in_left)
root.right = self.reConstructBinaryTree(pre_right, in_right)
return root