PAT 1119 Pre- and Post-order Traversals (30分)

探讨了如何根据前序和后序遍历序列确定二叉树的中序遍历是否唯一,通过分析节点的孩子状态,采用递归方法划分左右子树,最终输出中序遍历序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:1119 Pre- and Post-order Traversals (30分)
关键词:树的遍历、前序后序推中序

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.

Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first printf in a line Yes if the tree is unique, or No if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input 1:

7
1 2 3 4 6 7 5
2 6 7 4 5 3 1

Sample Output 1:

Yes
2 1 6 4 7 3 5

Sample Input 2:

4
1 2 3 4
2 4 3 1

Sample Output 2:

No
2 1 3 4

题目大意: 给出你一棵树的前序遍历和后序遍历,问你这棵树的中序遍历是否唯一,并输出中序遍历。

分析:
如果一个结点只有一个孩子,那么这个结点可是是左孩子也可以是右孩子,因此中序遍历就不唯一了;

柳神的做法:已知二叉树的前序和后序是无法唯一确定一颗二叉树的,因为可能会存在多种情况,这种情况就是一个结点可能是根的左孩子也有可能是根的右孩子,如果发现了一个无法确定的状态,置unique = 0,又因为题目只需要输出一个方案,可以假定这个不可确定的孩子的状态是右孩子,接下来的问题是如何求根结点和左右孩子划分的问题了,首先我们需要知道树的表示范围,需要四个变量,分别是前序的开始的地方prel,前序结束的地方prer,后序开始的地方postl,后序结束的地方postr,前序的开始的第一个应该是后序的最后一个是相等的,这个结点就是根结点,以后序的根结点的前面一个结点作为参考,寻找这个结点在前序的位置,就可以根据这个位置来划分左右孩子,递归处理

代码:

// pat 1119
#include <bits/stdc++.h>
using namespace std;

int n;
vector<int> pre, post, in;
bool flag = true;	//中序是否唯一 

void getIn(int prel, int prer, int postl, int postr){
	if(prel == prer){
		in.push_back(pre[prel]);
        return;
	}
	if(pre[prel] == post[postr]){	//这个位置是根结点 
		int i = prel + 1;
		while(i <= prer && pre[i] != post[postr - 1]) i ++;	//i找到后续遍历中根结点的前一个结点 
		if(i - prel > 1)
			getIn(prel + 1, i-1, postl, postl+(i-prel-1)-1); 
		else 
			flag = false;	//不唯一 
		in.push_back(post[postr]); 
        getIn(i, prer, postl + (i-prel-1), postr-1);
    }
}

int main(){
	scanf("%d", &n);
	pre.resize(n);
	post.resize(n);
	
	for(int i = 0; i < n; i ++ ) scanf("%d", &pre[i]);
	for(int i = 0; i < n; i ++ ) scanf("%d", &post[i]);
	
	getIn(0, n-1, 0, n-1); //或得中序序列 
	//输出 

	if(flag) puts("Yes");
	else puts("No"); 
	for(int i = 0; i < in.size(); i ++ ){
		if(i) printf(" ");
		printf("%d", in[i]);
	}
    printf("\n");	//不输出换行符就会格式错误
    	
	return 0;
} 

注意: 要在输出的结尾输出一个换行符,否则会格式错误!

American Heritage 题目描述 Farmer John takes the heritage of his cows very seriously. He is not, however, a truly fine bookkeeper. He keeps his cow genealogies as binary trees and, instead of writing them in graphic form, he records them in the more linear tree in-order" and tree pre-order" notations. Your job is to create the `tree post-order" notation of a cow"s heritage after being given the in-order and pre-order notations. Each cow name is encoded as a unique letter. (You may already know that you can frequently reconstruct a tree from any two of the ordered traversals.) Obviously, the trees will have no more than 26 nodes. Here is a graphical representation of the tree used in the sample input and output: C / \ / \ B G / \ / A D H / \ E F The in-order traversal of this tree prints the left sub-tree, the root, and the right sub-tree. The pre-order traversal of this tree prints the root, the left sub-tree, and the right sub-tree. The post-order traversal of this tree print the left sub-tree, the right sub-tree, and the root. ---------------------------------------------------------------------------------------------------------------------------- 题目大意: 给出一棵二叉的中遍历 (inorder)前序遍历 (preorder),求它的后序遍历 (postorder)。 输入描述 Line 1: The in-order representation of a tree. Line 2: The pre-o rder representation of that same tree. Only uppercase letter A-Z will appear in the input. You will get at least 1 and at most 26 nodes in the tree. 输出描述 A single line with the post-order representation of the tree. 样例输入 Copy to Clipboard ABEDFCHG CBADEFGH 样例输出 Copy to Clipboard AEFDBHGC c语言,代码不要有注释
最新发布
06-16
<think>我们已知二叉前序遍历和中遍历,可以唯一确定一棵二叉,并由此得到后序遍历。思路:1.前序遍历的第一个节点是根节点。2.在中遍历中找到根节点,则根节点左边是左子的中遍历,右边是右子的中遍历。3.根据左子的节点个数,可以在前序遍历中确定左子前序遍历和右子前序遍历。4.递归处理左子和右子。5.在递归构建二叉的过程中,我们按照后序遍历的顺(左子->右子->根节点)将节点值存入后序遍历数组。但是,题目要求直接生成后序遍历数组,而不需要构建整个二叉的结构。我们可以通过递归函数直接填充后序遍历数组。具体步骤:假设我们有一个全局数组(或通过参数传递的数组)`postorder`来存储后序遍历结果,以及一个全局索引(或指针)`post_idx`表示当前要填充的位置(注意:由于后序遍历是左右根,所以应该从后往前填充,或者按顺填充再调整,但这里我们可以在递归中按顺填充,但是需要确定根节点的位置在最后)。然而,我们也可以这样:后序遍历的顺是左、右、根。所以当我们递归处理完左子和右子后,将根节点放入后序遍历数组的当前位置。但是,由于我们是从前序遍历得到根节点,然后递归左子和右子,最后才处理根节点,所以我们可以按照这个顺直接填充。但是注意:我们构建后序遍历数组时,需要知道整个的节点数,并且从数组的末尾开始填充(因为根节点在最后)?或者也可以按左子、右子、根的顺依次放入数组,但这样需要知道左子和右子的大小,然后确定根节点在数组中的位置。另一种方法:我们可以在递归过程中,每次将根节点放到当前子对应后序遍历区间的最后一个位置。因此,我们可以传递后序遍历数组的起始和结束位置,但这样比较复杂。这里我们采用一种更简单的方法:递归地构建左右子,并按照后序遍历的顺(先左子,再右子,最后根节点)将节点值存入数组。我们使用一个全局数组和一个全局索引(从0开始),在递归左子和右子后,将根节点存入数组,然后索引递增。这样得到的数组顺就是后序遍历。然而,这样得到的数组顺是:先左子的所有节点(按照后序),然后右子的所有节点(按照后序),最后根节点。这符合后序遍历的定义。但是,注意:前序遍历数组和中遍历数组我们如何传递?我们每次递归需要传递当前子前序遍历列和中遍历列(在原始数组中的起始位置和长度)。或者传递指针和长度。由于C语言中数组是连续内存,我们可以通过指针和长度来传递子对应的部。设计递归函数:voidbuildPost(int*preorder,int*inorder,intn,int*postorder,int*postIndex)参数说明:preorder:当前子前序遍历数组的起始指针inorder:当前子的中遍历数组的起始指针n:当前子的节点个数postorder:后序遍历数组(全局)postIndex:当前后序遍历数组的填充位置(指针,因为递归中需要更新)递归过程:1.如果n==0,返回。2.前序遍历的第一个元素preorder[0]就是根节点。3.在中遍历数组inorder中找到根节点的位置,设为k(即inorder[k]==preorder[0])。那么,左子的节点个数为k,右子的节点个数为n-k-1。4.递归构建左子:buildPost(preorder+1,inorder,k,postorder,postIndex);5.递归构建右子:buildPost(preorder+1+k,inorder+k+1,n-k-1,postorder,postIndex);6.将根节点存入postorder[*postIndex],然后(*postIndex)++。注意:这样递归后,postorder数组中的顺就是后序遍历。但是,我们需要考虑如何在中遍历数组中找到根节点的位置。由于数组中可能有重复值?题目没有说明,通常假设节点值唯一。所以我们可以遍历inorder数组直到找到根节点。例子:前序遍历:[1,2,4,5,3,6,7]中遍历:[4,2,5,1,6,3,7]后序遍历:[4,5,2,6,7,3,1]递归过程:根节点1,在中遍历中找到1,位置为3(下标从0开始),则左子有3个节点(4,2,5),右子有3个节点(6,3,7)。左子前序遍历:从原前序遍历的第二个元素开始,取3个:[2,4,5]左子的中遍历:中遍历中1左边的3个元素:[4,2,5]递归左子:根节点2,在[4,2,5]中,2的位置是1,左子节点为1(4),右子节点为1(5)左子的左子前序遍历[4],中遍历[4]->递归后得到后序遍历:先处理左子(无,因为节点个数0),再处理右子(无),然后放入根节点4->所以后序遍历数组先放4。然后左子的右子前序遍历[5],中遍历[5]->放入5。然后左子的根节点2放入。所以左子后序遍历是[4,5,2]。同理,右子前序遍历[3,6,7],中遍历[6,3,7]->根节点3,在[6,3,7]中位置1,左子[6](1个节点),右子[7](1个节点)递归左子:放入6递归右子:放入7放入3所以右子后序遍历是[6,7,3]最后放入根节点1。整个后序遍历:[4,5,2,6,7,3,1]代码实现中,需要注意在中遍历中查找根节点时,如果节点值唯一,遍历即可。但是,这个递归函数需要每次在inorder中线性查找根节点,时间复杂度O(n),整个算法时间复杂度O(n^2)。对于较大的,可以考虑先用哈希表存储中遍历的值和索引(但题目要求C语言,且节点值如果是整数,且范围不大,可以用数组哈希,否则就线性查找)。由于题目没有说明节点值的范围,我们假设节点值为整数,且节点个数不会太大,所以采用线性查找。另外,递归函数中,我们每次传递的是当前子前序遍历数组的起始位置和中遍历数组的起始位置,以及节点个数。最后,我们还需要注意递归的终止条件:n==0。编写函数:输入:前序遍历数组pre,中遍历数组in,节点个数n输出:后序遍历数组post(需要提前配好空间,大小与n相同)步骤:1.初始化一个索引变量postIndex=0(注意在递归中需要传递它的地址,以便递归中更新)。2.调用递归函数buildPost(pre,in,n,post,&postIndex);3.递归函数结束后,post数组中就是后序遍历结果。注意:这个递归函数中,我们按照左子、右子、根的顺将节点值放入post数组,并且postIndex从0开始递增,所以最后post数组就是后序遍历。但是,我们也可以不用全局索引,而是通过递归函数的返回值?这里我们传递索引的指针。代码实现如下:</think>### 二叉后序遍历生成代码实现(C语言) 根据二叉前序遍历和中遍历生成后序遍历的核心思路是通过递归重建二叉结构,然后进行后序遍历输出。以下是完整实现代码: ```c #include <stdio.h> #include <stdlib.h> // 二叉节点结构 typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; // 创建新节点 TreeNode* createNode(int value) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); newNode->val = value; newNode->left = NULL; newNode->right = NULL; return newNode; } // 在中数组中找到根节点位置 int findRootIndex(int inorder[], int start, int end, int rootValue) { for (int i = start; i <= end; i++) { if (inorder[i] == rootValue) { return i; } } return -1; // 未找到 } // 根据前序和中重建二叉 TreeNode* buildTree(int preorder[], int inorder[], int preStart, int preEnd, int inStart, int inEnd) { if (preStart > preEnd || inStart > inEnd) return NULL; // 前序遍历第一个元素是根节点 int rootValue = preorder[preStart]; TreeNode* root = createNode(rootValue); // 在中中找到根节点位置 int rootIndex = findRootIndex(inorder, inStart, inEnd, rootValue); int leftSubtreeSize = rootIndex - inStart; // 递归构建左子 root->left = buildTree( preorder, inorder, preStart + 1, preStart + leftSubtreeSize, inStart, rootIndex - 1 ); // 递归构建右子 root->right = buildTree( preorder, inorder, preStart + leftSubtreeSize + 1, preEnd, rootIndex + 1, inEnd ); return root; } // 后序遍历二叉并存储结果 void postorderTraversal(TreeNode* root, int result[], int* index) { if (!root) return; postorderTraversal(root->left, result, index); postorderTraversal(root->right, result, index); result[(*index)++] = root->val; } // 释放二叉内存 void freeTree(TreeNode* root) { if (!root) return; freeTree(root->left); freeTree(root->right); free(root); } // 主函数:生成后序遍历 void getPostorder(int preorder[], int inorder[], int n, int postorder[]) { TreeNode* root = buildTree(preorder, inorder, 0, n - 1, 0, n - 1); int index = 0; postorderTraversal(root, postorder, &index); freeTree(root); } // 测试用例 int main() { // 示例输入(前序和中遍历列) int preorder[] = {3, 9, 20, 15, 7}; int inorder[] = {9, 3, 15, 20, 7}; const int n = sizeof(preorder) / sizeof(preorder[0]); // 生成后序列 int postorder[n]; getPostorder(preorder, inorder, n, postorder); // 打印结果 printf("生成的后序遍历列: "); for (int i = 0; i < n; i++) { printf("%d ", postorder[i]); } printf("\n"); // 输出: 9 15 7 20 3 return 0; } ``` ### 关键步骤说明: 1. **重建二叉**(`buildTree`函数): - 前序列的第一个元素总是当前子的根节点 - 在中列中找到根节点位置,左侧为左子,右侧为右子 - 递归处理左子和右子[^3] 2. **后序遍历**(`postorderTraversal`函数): - 遍历:左子 → 右子 → 根节点 - 结果按顺存储到输出数组[^2] 3. **空间管理**: - 使用`freeTree`释放动态配的节点内存 - 时间复杂度:$O(n^2)$(可优化为$O(n)$) - 空间复杂度:$O(n)$ ### 算法优化方向: 1. **查找优化**:使用哈希表存储中列的值-索引映射,将查找操作从$O(n)$降至$O(1)$ 2. **迭代实现**:改用栈替代递归,避免栈溢出风险 3. **直接生成**:不构建完整二叉,直接在递归过程中填充后序数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值