Pat(Advanced Level)Practice--1020(Tree Traversals)

Pat1020代码

题目描述:

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 7
Sample Output:
4 1 6 3 5 7 2

AC代码:
#include<cstdio>
#include<cstdlib>
#include<queue>
#define MAX 35

using namespace std;

typedef struct Node
{
	int data;
	struct Node *left;
	struct Node *right;
}Node;

Node* ReBuild(int *Porder,int *Inorder,int len)
{
	Node *root=(Node *)malloc(sizeof(Node));
	if(!root)
	{
		printf("No enough memory!\n");
		exit(-1);
	}
	if(len<=0)
		return NULL;
	root->left=NULL;
	root->right=NULL;
	root->data=Porder[len-1];
	int i=0;
	for(i=0;i<len;i++)
		if(Porder[len-1]==Inorder[i])
			break;
	root->left=ReBuild(Porder,Inorder,i);
	root->right=ReBuild(Porder+i,Inorder+i+1,len-i-1);
	return root;
}

void LevelOrder(Node *root)
{
	int first=1;
	queue<Node *> q;
	if(root!=NULL)
		q.push(root);
	while(!q.empty())
	{
		Node *temp;
		temp=q.front();
		if(temp->left!=NULL)
			q.push(temp->left);
		if(temp->right!=NULL)
			q.push(temp->right);
		if(first)
		{
			printf("%d",temp->data);
			first=0;
		}
		else
			printf(" %d",temp->data);
		q.pop();
	}
	printf("\n");
}

int main(int argc,char *argv[])
{
	int n;
	int i,j;
	int Porder[MAX],Inorder[MAX];
	scanf("%d",&n);
	for(i=0;i<n;i++)
		scanf("%d",&Porder[i]);
	for(j=0;j<n;j++)
		scanf("%d",&Inorder[j]);
	Node *tree=ReBuild(Porder,Inorder,n);
	LevelOrder(tree);

	return 0;
}

重构二叉树是很经典的一个题目。

你可能感兴趣的:(C++,二叉树,pat,基础题,advance)