程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Pat(Advanced Level)Practice--1020(Tree Traversals)

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

編輯:C++入門知識

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
#include
#include
#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;ileft=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 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

重構二叉樹是很經典的一個題目。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved