第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def buildTree(inorder, postorder):
if not postorder:
return None
root = TreeNode(postorder[-1])
root_idx = inorder.index(root.val)
root.right = buildTree(inorder[root_idx+1:], postorder[root_idx:-1])
root.left = buildTree(inorder[:root_idx], postorder[:root_idx])
return root
n = int(input())
postorder = list(map(int, input().split()))
inorder = list(map(int, input().split()))
root = buildTree(inorder, postorder)
一定要注意这里是齐次多项式
从所得到的A矩阵中,我们可以看出,矩阵对角线上的元素决定了平方项的系数,
而交叉项的系数被平均分配到了相应矩阵的位置中,
根据这条规律,我们就可以根据所给的二次型的代数形式直接写出相应的矩阵形式。
我可以提供以下信息:
二叉树的节点个数是N。
后序遍历结果是一个长度为N的整数序列,用空格分隔表示;中序遍历结果是一个长度为N的整数序列,用空格分隔表示。
关于后序遍历和中序遍历构建二叉树的先序遍历,可以采用递归的方法进行构建,具体步骤如下:
根据后序遍历结果,最后一个节点为根节点。
在中序遍历结果中,找到根节点所在的位置,该位置左边为左子树节点,右边为右子树节点。
根据左子树节点个数,划分后序遍历结果的左、右子树部分。
对左、右子树部分分别递归进行构建二叉树,得到左、右子树的先序遍历。
将根节点和左、右子树的先序遍历拼接起来,得到完整的先序遍历结果。
具体的Python代码如下:
class TreeNode: """定义二叉树节点类"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def build_tree(inorder, postorder): """根据中序遍历和后序遍历构建二叉树"""
# 当序列为空时,返回None
if not inorder or not postorder:
return None
# 后序遍历的最后一个节点为根节点
root_val = postorder[-1]
root = TreeNode(root_val)
# 在中序遍历中找到根节点
root_index = inorder.index(root_val)
# 划分左子树和右子树
left_inorder = inorder[:root_index]
right_inorder = inorder[root_index + 1:]
left_postorder = postorder[:root_index]
right_postorder = postorder[root_index:-1]
# 递归构建左子树和右子树
root.left = build_tree(left_inorder, left_postorder)
root.right = build_tree(right_inorder, right_postorder)
return root
def preorder(root): """输出二叉树的先序遍历"""
if root is None:
return []
res = [root.val]
res += preorder(root.left)
res += preorder(root.right)
return res
N = int(input())
inorder = list(map(int, input().split())) postorder = list(map(int, input().split()))
root = build_tree(inorder, postorder) result = preorder(root) print(*result)
需要注意的是,在Python中,可以通过*将列表展开成为函数的参数列表,这样可以方便地将列表中的数值用空格隔开输出。