A1064

沒寫出.
本題是由已知完全二叉樹遍歷得到中序遍歷序列的逆用.
已知完全二叉樹中序遍歷序列以及樹的輪廓,有了樹的輪廓框架,即可進行中序遍歷,從而將中序遍歷序列中的值依次填充到樹的框架中,充實樹,最後得到完整的樹(擁有權重即每個結點的值).
用數組存儲,遍歷過程與鏈表一致,由root2代替root->lchild,root2+1代替root->rchild.
同類型題:A1099

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=1010;
int a[maxn],res[maxn],idx=0;
void order(int root,int n){            //完全二叉樹中序遍歷的逆用. 
	if(root>n){
		return;
	}
	order(root*2,n);
	res[root]=a[idx++];
	order(root*2+1,n);
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	sort(a,a+n);
	order(1,n);
	for(int i=1;i<=n;i++){
		printf("%d",res[i]);
		if(i!=n){
			printf(" ");
		}
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章