📅  最后修改于: 2023-12-03 15:28:41.410000             🧑  作者: Mango
本题来自于《GATE-CS-2002》的第44题,要求针对给定的数据结构进行遍历操作。
设一棵二叉树的先序遍历序列为:$1, 2, 4, 5, 3, 6, 7$,中序遍历序列为:$4, 2, 5, 1, 6, 3, 7$。则这棵二叉树的后序遍历序列是什么?
首先要知道二叉树的先序遍历、中序遍历和后序遍历的定义:
由于本题已给出先序遍历序列和中序遍历序列,因此可以按以下步骤进行求解:
def post_order(in_order, pre_order):
if not in_order:
return []
root = pre_order[0]
root_index = in_order.index(root)
left_in_order = in_order[:root_index]
right_in_order = in_order[root_index + 1:]
left_pre_order = pre_order[1:len(left_in_order) + 1]
right_pre_order = pre_order[len(left_in_order) + 1:]
left_post_order = post_order(left_in_order, left_pre_order)
right_post_order = post_order(right_in_order, right_pre_order)
return left_post_order + right_post_order + [root]
in_order = [4, 2, 5, 1, 6, 3, 7]
pre_order = [1, 2, 4, 5, 3, 6, 7]
post_order = post_order(in_order, pre_order)
print(post_order) # 输出结果:[4, 5, 2, 6, 7, 3, 1]
以上python代码可以求出该二叉树的后序遍历序列,输出结果为$[4, 5, 2, 6, 7, 3, 1]$。