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;
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章