Traverse of PTA L2-006 Trees (25 points)

Title Description:

Given a binary tree's post-order traversal and intermediate-order traversal, please output the sequence of its sequence traversal. It is assumed that the key values are positive integers that are not equal to each other.

Input format:

The first line of input gives a positive integer N (< 30), which is the number of nodes in the binary tree. The second line gives the sequential traversal sequence. The third line gives the order traversal sequence. Numbers are separated by spaces.

Output format:

Output the sequence of sequential traversal of the tree in a row. Numbers are separated by one space, and no extra space is allowed at the beginning and end of the line.

Input sample:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Output sample:

4 1 6 3 5 7 2

Ideas for problem solving:

This problem is the traversal of given post-order and middle-order. The root node can be determined by post-order. The middle-order can be divided into left subtree and right subtree and root node by root node. Then, the latter can be divided into left subtree and right subtree and root node by left subtree and right subtree. Then, in fact, this process is repeated to build a tree. Finally, the sequence traversal is done by extensive search.

AC Code:

#include <iostream>
#include<stdio.h>
using namespace std;
int tree[5000];
int a;
void gettree(int b[500],int c[500],int num,int tb,int tc)
{
	if(tb==0||tc==0)
	{
		return;
	}
	int b1[35];
	int c1[35];
	int tb1=0;
	int tc1=0;
	int n=0;
	for(n=0;n<tc;n++)
	{
		if(c[n]==b[tb-1])
		{	
			gettree(b1,c1,num*2+1,tb1,tc1);
			tree[num]=c[n];
			break;
		}
		b1[tb1]=b[n];
		tb1++;
		c1[tc1]=c[n];
		tc1++;
	}
	tb1=0;
	tc1=0;
	int u=n;
	n++;
	while(n<tc)
	{
		b1[tb1]=b[u];
		c1[tc1]=c[n];
		n++;
		u++;
		tb1++;
		tc1++;
	}
	gettree(b1,c1,num*2+2,tb1,tc1);
}
int flag6=0;
void bfs(int dui[35],int num)
{
	if(num==0)
	{
		return;
	}
	int dui1[35];
	int num1=0;
	for(int n=0;n<num;n++)
	{
		if(flag6==0)
		{
			printf("%d",tree[dui[n]]);
			flag6=1;
		}
		else
		{
			printf(" %d",tree[dui[n]]);
		}
		if(tree[dui[n]*2+1]!=-1)
		{
			dui1[num1]=dui[n]*2+1;
			num1++;
		}
		if(tree[dui[n]*2+2]!=-1)
		{
			dui1[num1]=dui[n]*2+2;
			num1++;
		}
	}
	bfs(dui1,num1);
}
int main(int argc, char *argv[]) {
	scanf("%d",&a);
	int b[500],c[500];
	for(int n=0;n<5000;n++)
	{
		tree[n]=-1;
	}
	for(int n=0;n<2;n++)
	{
		for(int m=0;m<a;m++)
		{
			int t;
			scanf("%d",&t);
			if(n==0)
			{
				b[m]=t;
			}
			else
			{
				c[m]=t;
			}
		}
	}
	gettree(b,c,0,a,a);
	int dui[200];
	dui[0]=0;
	bfs(dui,1);
	return 0;
}

 

Posted by kannu on Tue, 08 Oct 2019 20:54:17 -0700