(补)算法刷题Day17:BM40 重建二叉树
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def constructTree(preOrder,vinOrder):
# 递归退出条件
if len(preOrder) == 0:
return None
# 根节点
root_val = preOrder[0]
root = TreeNode(root_val)
index = vinOrder.index(root_val)
# 左子树
leftnode = constructTree(preOrder[1:index+1], vinOrder[:index])
# 柚子树
rightnode = constructTree(preOrder[index+1:],vinOrder[index+1:])
root.left = leftnode
root.right = rightnode
return root
class Solution:
def reConstructBinaryTree(self , preOrder: List[int], vinOrder: List[int]) -> TreeNode:
# write code here
# 根据前序遍历确定中间节点,根据中序遍历,分左右子树
return constructTree(preOrder,vinOrder)