现在的位置: 首页 > 综合 > 正文

浙大PAT 1020题 1020. Tree Traversals

2018年05月26日 ⁄ 综合 ⁄ 共 1245字 ⁄ 字号 评论关闭

已知树的后序和中序遍历,输出这树的层次遍历。

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
typedef struct NodeType{
	int value;
	struct NodeType *left;
	struct NodeType *right;
}Node;
int a[32],b[32];
Node* BuildTree(int* da,int* db,int n){
	int i,j;
	if(n<=0){
		return NULL;	
	}
	for(i=0;i<n;i++){
		if(*(db+i)==*(da+n-1)){
			break;
		}
	}
	Node* node=(Node*)malloc(sizeof(Node));
	node->value=*(da+n-1);
	node->left=BuildTree(da,db,i);
	node->right=BuildTree(da+i,db+i+1,n-1-i);
	return node;
}
void Delloc(Node* node){
	if(node==NULL) return;
	Delloc(node->left);
	Delloc(node->right);
	free(node);	
}
//use for test
void PrintPreorderTree(Node* node){
	if(node==NULL) return;
	printf("%d ",node->value);
 	PrintPreorderTree(node->left);
  	PrintPreorderTree(node->right);
}
void PrintLevelorderTree(Node* node){
	queue<Node*>q;
	q.push(node);
	printf("%d",node->value);
	q.pop();
	if(node->left!=NULL)
			q.push(node->left);
	if(node->right!=NULL)
			q.push(node->right);
	while(!q.empty()){
		Node* tmp=q.front();
		q.pop();
		printf(" %d",tmp->value);
		if(tmp->left!=NULL)
			q.push(tmp->left);
		if(tmp->right!=NULL)
			q.push(tmp->right);
	}
	printf("\n");
}
int main(){
	int i,j,n;
	scanf("%d",&n);
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	for(i=0;i<n;i++){
		scanf("%d",&b[i]);
	}
	Node* root=BuildTree(a,b,n);
	//PrintPreorderTree(root);
	PrintLevelorderTree(root);
	Delloc(root);
	return 0;
}

 

抱歉!评论已关闭.