根据后序和中序求先序:
按照常规思路递归实现,先递归生成左子树,再递归生成右子树
class node: #定义节点结构
def __init__(self, value = None, left = None, right=None):
self.value = value
self.left = left
self.right = right
def GetTwoTree(str1, str2): #str1为后序 str2为中序
root = node(str1[-1]) #先给第一个值
Index = str2.index(root.value) #根在中序中的索引
leftstr2 = str2[: Index] #中序中的左半部分
maxindex = -1
for i in leftstr2: # 分离后序序列
tmpindex = str1.index(i)
if maxindex < tmpindex:
maxindex = tmpindex
if len(leftstr2) == 1: #如果只有一个元素
root.left = node(leftstr2) #直接赋值
elif len(leftstr2) == 0: #如果没有元素
root.left = None #空
else: #否则递归
root.left = GetTwoTree(str1[:maxindex+1], leftstr2) #递归构造左子树
rightstr2 = str2[Index+1:] #中序中的右半部分
if len(rightstr2) == 1:
root.right = node(rightstr2)
elif len(rightstr2) == 0:
root.right = None
else:
root.right = GetTwoTree(str1[maxindex+1:-1], rightstr2) #递归构造右子树
return root
def preTraverse(root): #递归先序遍历
if root != None:
print(root.value)
preTraverse(root.left)
preTraverse(root.right)
if __name__ == '__main__':
str1 = 'FCDBGEA' #str1为后序结果 str2为中序结果
str2 = 'CFBDAEG'
root = GetTwoTree(str1, str2) #构造二叉树
preTraverse(root) #遍历输出
补充:
根据完全二叉树的层次遍历序列顺序构造二叉树
class node:
def __init__(self, value = None, left = None, right = None):
self.value = value
self.left = left
self.right = right
Quepre = [0,1,2,3,4,5,6]
Que = [0] #保证原序列从1开始编号
for i in Quepre:
Que.append(node(i))
for i in range(1, len(Que)//2):
Que[i].left = Que[i*2]
Que[i].right = Que[i*2+1]
def preTraverse(root): # 递归先序遍历
if root != None:
print(root.value)
preTraverse(root.left)
preTraverse(root.right)
preTraverse(Que[1])