# -*- 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:
return None
root=TreeNode(pre[0])
pos=tin.index(pre[0])
root.left=self.reConstructBinaryTree(pre[1:1+pos],tin[:pos])
root.right=self.reConstructBinaryTree(pre[pos+1:],tin[pos+1:])
return root
以题目中的例子为例:输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
前序遍历从根节点开始,所以pre[0]就是root,中序遍历是先遍历左子树后遍历根节点,所以在tin中索引pos[0]的位置,将tin分为左右两个子树,再分别进行构造。注意root的left和right的边界,tin的边界比较好理解,pre的left边界要将pre[0]去掉,所以从pre[1]开始,tin中左子树有index个元素(不含root),在pre中左子树的范围就是1:1+index