L2-011. Play with binary tree
Given the middle order traversal and the pre order traversal of a binary tree, please make a mirror reversal of the tree first, and then output the sequence of sequence traversal after reversal. The so-called mirror reversal refers to the exchange of left and right children of all non leaf nodes. It is assumed that all key values are positive integers that are not equal to each other.
Input format:
Enter the first line to give a positive integer N (< 30), which is the number of nodes in the binary tree. The second line gives the order traversal sequence. The third line gives the sequence of its preorder traversal. Numbers are separated by spaces.
Output format:
Output the sequence traversal sequence after the tree reversal in a row. Numbers are separated by one space, and there must be no extra space at the beginning and end of the line.
Input example:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
Output example:
4 6 1 7 5 3 2
Note: when calculating the binomial tree mirror, first store the right subtree of the sequence.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node*l,*r;
}node,*Tree;
int zhong[40],qian[40];
struct node*creat(int zhong[],int qian[],int n)
{
if(n<=0)
return NULL;
Tree T;
int p = qian[0];
T = (node*)malloc(sizeof(node));
T->data = p;
int k;
for(int i=0;i<n;i++)
{
if(zhong[i] == p)
{
k = i;
break;
}
}
T->l = creat(zhong,qian+1,k);
T->r = creat(zhong+k+1,qian+k+1,n-k-1);
return T;
};
void cengxu(Tree&T)
{
Tree a[40];
int n=0,i=0;
a[n++] = T;
while(i<n)
{
if(a[i])
{
if(a[i]->r!=NULL)
a[n++] = a[i]->r;
if(a[i]->l!=NULL)
a[n++] = a[i]->l;
}
i++;
}
for(i=0;i<n-1;i++)
printf("%d ",a[i]->data);
printf("%d\n",a[n-1]->data);
}
int main()
{
int n,i;
Tree T;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&zhong[i]);
for(i=0;i<n;i++)
scanf("%d",&qian[i]);
T = creat(zhong,qian,n);
cengxu(T);
return 0;
}