Know the post-order and in-order traversal results of the binary tree to find the pre-order result

Description

The problem is very simple, give you the post-order and in-order sequence of a binary tree, and find its pre-order sequence (So easy!).

Input

Enter multiple sets of data (less than 100 sets), ending with the end of the file.
Each set of data consists of only one line, including two strings, separated by spaces, representing the post-order and in-order sequences of the binary tree respectively (the length of the string is less than 26, and the input data is guaranteed to be legal).

Output

Each set of output data occupies a separate line, and the output corresponds to a pre-order sequence.

Sample Input

ACBFGED ABCDEFG
CDAB CBAD

Sample Output

DBACEGF
BCAD

Recursive idea:

Find the root node from the post-order sequence, traverse the in-order sequence after finding it, and divide it into a left subtree and a right subtree with the root node as the boundary

print root node

recursive left subtree

recursive right subtree

Implementation steps:

1. The post-order is stored in the string array a, and the mid-order is stored in the string array b

2. The recursive function needs to receive three variables (1) the position of the root node in a (2) the starting position of the part operated in b

void recovery(int root,int start,int end)

3. After entering the function, traverse b, find the root node position, and use i to store the position

4. Print the root node

5. Recursive left subtree

ps: Note here that the start, end and root to be passed recursively at this time are for the left subtree ABC

So, root=toot-(end-i)-1; start unchanged; end=i-1;

6. Recursive right subtree

The same for EFG root=root-1; start=i+1; end unchanged;

Note: When end==start, the current node is already a leaf node, so when start>end, it is the recursive end condition.

Code:

#include<stdio.h>
#include<string.h>
void recovery(int root,int start,int end);
char a[1000];
char b[1000];
intmain()
{
	while(scanf("%s",a)==1)
	{
		scanf("%s",b);
		int l=strlen(a);
		recovery(l-1,0,l-1);
		printf("\n");
	}
}
void recovery(int root,int start,int end)
{
	if(start>end)
	return ;
	int i=start;//i is used to traverse
	while(i<end&&b[i]!=a[root])//traverse b to find the root node  
	i++;
	printf("%c",a[root]);//Print the root node
	recovery(root-(end-i)-1,start,i-1);//traverse the left subtree
	recovery(root-1,i+1,end);//traverse the right subtree
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324814376&siteId=291194637