PAT甲级 1020 Tree Traversals (25分)

一道建树的标准题,先把递归把树建起来,再用队列输出。一开始自己也忘得差不多了,也是学习了别人的代码,要好好巩固巩固才行。。。

#include<bits/stdc++.h>
using namespace std;
int post[50];
int in[50];
struct node{
	int data;
	node* left;
	node* right;
};
node* BuildTree(int postL,int postR,int inL,int inR)
{
	if(postL > postR)
	return NULL;
	int k;
	for(k = inL;k<=inR;k++)
	{
		if(in[k] == post[postR])
		break;
	}
	int num = k - inL;
	node* root = new node;
	root->data = post[postR];
	root->left = BuildTree(postL,postL+num-1,inL,k-1);
	root->right = BuildTree(postL+num,postR-1,k+1,inR);
	return root;
}
main()
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	scanf("%d",&post[i]);
	for(int i=0;i<n;i++)
	scanf("%d",&in[i]);
	node* root = BuildTree(0,n-1,0,n-1);
	queue<node*> q;
	int cnt = 0;
	q.push(root);
	while(q.empty()==0)
	{
		node* temp = q.front();
		q.pop();
		if(cnt==0)
		{
			printf("%d",temp->data);
			cnt++;
		}
		else
		printf(" %d",temp->data);
		if(temp->left)
		q.push(temp->left);
		if(temp->right)
		q.push(temp->right);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章