PTA L2-006 树的遍历 团体程序设计天梯赛(C++代码)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2

给定一棵二叉树的后序遍历和中序遍历,输出前序代码:

#include <bits/stdc++.h>
using namespace std;
int post[35],in[35];
void helper(int root,int start,int end){
	if(start > end) return ;
	int l = start;
	while(l < end && in[l] != post[root]) l++;
	printf("%d ",post[root]);
	//end-l为当前右孩子的个数,root - (end - l) - 1则为当前左子树的根
	helper(root - (end - l) - 1,start,l-1);
	//root-1位当前右子树的根
	helper(root-1,l+1,end);
}
int main(){
	int n;
	cin>>n;
	for(int i = 0;i < n;i++) cin>>post[i];
	for(int i = 0;i < n;i++) cin>>in[i];
	helper(n-1,0,n-1);
	return 0;
}

本题的ac代码:

#include <bits/stdc++.h>
using namespace std;
int post[35],in[35],res[10010];
void helper(int root,int start,int end,int index){
	if(start > end) return ;
	int l = start;
	while(l < end && in[l] != post[root]) l++;
	res[index] = post[root];
	helper(root - (end - l) - 1,start,l-1,2*index+1);
	helper(root-1,l+1,end,2*index+2);
}
int main(){
	int n;
	cin>>n;
	for(int i = 0;i < n;i++) cin>>post[i];
	for(int i = 0;i < n;i++) cin>>in[i];
	helper(n-1,0,n-1,0);
	int cnt = 0;
	for(int i = 0;i < 10010;i++){
		if(cnt == n-1 && res[i] != 0)
		{
			cout<<res[i];
			break;
		}
		else if(res[i] != 0){
			cout<<res[i]<<" ";
			cnt++;
		}
	}
	return 0;
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章