1.使用递归方法
# 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:
return None
else:
treenode=TreeNode(pre[0])
target=tin.index(pre[0])#根节点位置
pre_left=pre[1:target+1]
pre_right=pre[target+1:]
tin_left=tin[0:target]
tin_right=tin[target+1:]
treenode.left=self.reConstructBinaryTree(pre_left, tin_left)#左子树继续构造二叉树,相当于用pre_left和tin_left两个前序和中序继续构造
treenode.right=self.reConstructBinaryTree(pre_right, tin_right)
return treenode