PAT A1020 Tree Traversals 树的遍历

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

假设一颗二叉树的所有键值都是不同的正数,给出后序遍历和中序遍历。你需要输出正确的层次遍历

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

第一行给出一个正数N,二叉树中所有节点数目。第二行是后序遍历,第三行是中序遍历。

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

注意最后一个数后面没有空格。

思路:先根据后序序列和中序序列把二叉树构建出来在进行层次遍历。

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>

using namespace std;
const int maxn = 50;

struct node{
	int data;
	node* lchild;
	node* rchild;
};

int in[maxn],post[maxn];//分别存放中序、后序遍历序列 
int n;//结点个数

//当前二叉树的后序序列区间为[postL,postR] 
//中序序列区间为[inL,inR]
//create函数返回构建出的二叉树的根节点地址 
node* create(int postL,int postR,int inL,int inR){
	if(postL>postR){
		return NULL;//后序序列长度小于等于0时,直接返回 
	}
	node* root = new node;//新建一个结点,用来存放当前二叉树的根节点 
	root ->data = post[postR];
	int k;
	//在中序遍历中找到根节点的位置 
	for(k=inL;k<=inR;k++){
		if(in[k]==post[postR]){
			break;
		}
	} 
	int numLeft = k-inL;//左子树结点个数
	//返回左子树的根节点地址,赋值给root左指针
	root->lchild=create(postL,postL+numLeft-1,inL,k-1);
	root->rchild=create(postL+numLeft,postR-1,k+1,inR);
	return root;//返回根节点地址 
} 

int num=0;//已输出的结点个数
//广度优先遍历-层次遍历 
void BFS(node* root){
	queue<node*> q;//注意队列里是存地址
	q.push(root);
	while(!q.empty()){
		node* now = q.front();//取出队首元素
		q.pop();
		printf("%d",now->data);//访问队首元素
		num++;
		if(num<n) printf(" ");
		if(now->lchild!=NULL) q.push(now->lchild);
		if(now->rchild!=NULL) q.push(now->rchild);
	} 
} 

int main(){
	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 = create(0,n-1,0,n-1);
	BFS(root);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/86026261
今日推荐