# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre)==0 or len(tin)==0:
return None
if len(pre)==len(tin)==1:
root= TreeNode(pre[0])
return root
root=TreeNode(pre[0])
index=tin.index(root.val)
tin_left=tin[:index]
tin_right=tin[index+1:]
left_length=len(tin_left)
pre_left=pre[1:left_length+1]
pre_right=pre[left_length+1:]
root.left=self.reConstructBinaryTree(pre_left,tin_left)
root.right=self.reConstructBinaryTree(pre_right,tin_right)
return root
原文:https://www.cnblogs.com/hit-joseph/p/9503380.html