1020. Tree Traversals (25)
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.
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.
Sample Input:7 2 3 1 5 7 6 4 1 2 3 4 5 6 7Sample Output:
4 1 6 3 5 7 2
发现PAT很爱考二叉树,这道题要求给出后序和中序遍历,让你输出层序遍历的结果。没什么好说的,基础题,刷题必须掌握的。
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <queue>
using namespace std;
typedef struct node {
int data;//节点数据元素
struct node *lchild;//指向左孩子
struct node *rchild;//指向右孩子
} BiNode,*BTree;
void GetPreOrder( char *last, char *mid, BTree &T, int len ) {//利用后序和中序建立二叉树
//printf("%c %c %d\n",*last,*mid,len);
if( len == 0 ) {
T = NULL;
return;
} //取出后序序列中的最后一个节点
int ch = last[len - 1];
int index = 0; //在中序序列中进行查找根节点,并用index记录其在序列中的索引
while( mid[index] != ch ) {
index++;
}
T = ( BTree )malloc( sizeof( BiNode ) ); //给根节点分配空间
T->data = mid[index];
GetPreOrder( last, mid, T->lchild, index );//建立左子树
GetPreOrder( last + index, mid + index + 1, T->rchild, len - index - 1 );//建立右子树
}
void GetPostOrder( char *prim, char *mid, BTree &T, int len ) {//利用先序和中序建立二叉树
if( len == 0 ) {
T = NULL;
return;
} //提出先序序列中的第一个节点
int ch = prim[0];
int index = 0; //在中序序列中查找当前根节点,并用index记录其在序列中的位置
while( mid[index] != ch ) {
index++;
} //给根节点分配空间
T = ( BTree )malloc( sizeof( BiNode ) );
T->data = mid[index]; //建立左子树
GetPostOrder( prim + 1, mid, T->lchild, index ); //建立右子树
GetPostOrder( prim + index + 1, mid + index + 1, T->rchild, len - index - 1 );
}
void PreOrder( BTree T ) {//先序输出二叉树
if( T != NULL ) {
printf( "%d", T->data );
PreOrder( T->lchild );
PreOrder( T->rchild );
}
}
void PostOrder( BTree T ) {//后序输出二叉树
if( T != NULL ) {
PostOrder( T->lchild );
PostOrder( T->rchild );
printf( "%d", T->data );
}
}
//层序遍历
void LeveOrder( BTree T ) {
int i = 0;
BTree p = T;
queue<BTree> queue;
queue.push( p );
while( !queue.empty( )) {
p = queue.front();
if( i == 0 )
printf( "%d", p->data );
else
printf( " %d", p->data );
queue.pop();
if( p->lchild != NULL ) {
queue.push( p->lchild );
}
if( p->rchild != NULL ) {
queue.push( p->rchild );
}
i++;
}
}
int main() {
char first[50], mid[50], last[50];
int n;
scanf( "%d", &n );
for( int i = 0; i < n; i++ ) {
scanf( "%d", &last[i] );
}
for( int i = 0; i < n; i++ ) {
scanf( "%d", &mid[i] );
}
BTree T = NULL;
GetPreOrder( last, mid, T, strlen( last ) );
LeveOrder( T );
return 0;
}