Traverse of 7-2 Trees (25 points)

Posted by zunebuggy on Tue, 08 Oct 2019 13:05:51 +0200

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

#include<stdio.h>
#include<malloc.h>
int N = 0;
int PreOrder[33] = { '\0' };//Middle order
int PostOrder[33] = { '\0' };//Post order
typedef struct node {
	int num;
	struct node* left;
	struct node* right;
}node;
struct node *create(int pos[], int pre[], int n);
void sequence(node *T);//Sequence Sort Output
int main(void)
{	
	node *T = NULL;//Constructing Binary Tree
	scanf("%d", &N);
	int i = 0;
	for (i = 0; i < N; i++)
		scanf("%d", &PostOrder[i]);
	for (i = 0; i < N; i++)
		scanf("%d", &PreOrder[i]);
	T = create(PostOrder, PreOrder, N);
	sequence(T);
	return 0;
}
void sequence(node *T)
{
	struct node *p[33], *q;
	int f = 0, r = 0;
	int num = 0;
	if (T) {
		p[r++] = T;//Root node queues
		while (f != r) {//The head of a team is not equal to the end of the team.
			q = p[f++];//Team out
			printf("%d", q->num);
			num++;//Counting Output Spaces
			if (num < N)
				printf(" ");
			if (q->left)//The left tree is not empty, join the team
				p[r++] = q->left;
			if (q->right)//The right tree is not empty, join the team
				p[r++] = q->right;
		}
	}
}
struct node *create(int pos[], int pre[], int n) {
	int i = 0, k = 0, root = 0;
	if (n == 0)  return NULL;
	struct node *T;
	T = (struct node *)malloc(sizeof(struct node));
	if (T == NULL)//Allocating Node Memory and Determining Success
		return NULL;
	root = pos[n - 1];//The root node is the last post-order traversal
	T->num = root;
	for (i = 0; i<n; i++){
		if (pre[i] == root){ //Determining the Length of Left and Right Subtrees by Mid-order Traversal
			k = i;
			break;
		}
	}
	T->left = create(pos, pre, k);//Recursive left and right subtrees
	T->right = create(pos + k, pre + k + 1, n - k - 1);
	return T;
}