树的基本构造与遍历

题目:1020. Tree Traversals (25)

 

题目描述:

已知树的postorder(后序遍历)与inorder(中序遍历),构造出完整的树,并按层次遍历输出数

 

代码展示一(已知后与中,进行层次遍历):

 

#include 
#include 
using namespace std;

const int maxn=1e3+5;
int a[maxn],b[maxn];
struct Tree{
	Tree *left,*right;
	int data;
};

Tree *buildtree(int la,int ra,int lb,int rb){
	if (la>ra) return NULL;
	int p;
	for (int i=lb;i<=rb;i++) 
		if (b[i]==a[ra]) {
			p=i;
			break;
		}
	Tree *tree=new Tree;
	tree->data  = a[ra];
	tree->left  = buildtree (la,la+(p-lb)-1,lb,p-1);
	tree->right = buildtree (la+(p-lb),ra-1,p+1,rb);
	return tree;
}
void print_levelorder(Tree *root){
	queue < Tree * > q;
	q.push(root);
	while(!q.empty()){
		Tree *tree=new Tree;
		tree=q.front();
		q.pop();
		cout<<" "<data;
		if (tree->left!=NULL)  q.push(tree->left);
		if (tree->right!=NULL) q.push(tree->right);
	}
}
int main(){
//	freopen("datain.txt","r",stdin);
	int n;
	cin>>n;
	for (int i=1;i<=n;i++) cin>>a[i];
	for (int i=1;i<=n;i++) cin>>b[i];
	Tree *root=buildtree(1,n,1,n);
	print_levelorder(root);
}

 

 

代码展示二(已知前与中,进行层次遍历):

只需更改建树的部分代码即可

 

Tree *buildtree(int la,int ra,int lb,int rb){
	if (la>ra) return NULL;
	int p;
	for (int i=lb;i<=rb;i++) 
		if (b[i]==a[la]) {
			p=i;
			break;
		}
	Tree *tree=new Tree;
	tree->data  = a[la];
	tree->left  = buildtree (la+1,la+(p-lb),lb,p-1);
	tree->right = buildtree (la+(p-lb)+1,ra,p+1,rb);
	return tree;
}

 

 

 

 

 

 

你可能感兴趣的:(树的基本构造与遍历)