We know how to travel around a binary tree in three depth priorities to get the root sequence, the previous root sequence, and the posterior root sequence. Conversely, if a binary tree is given the root sequence and the post root sequence, or given the root sequence and the previous root sequence, a one or two-fork tree can be reconstructed. The root sequence and the post root sequence of a binary tree are required to reconstruct the binary tree in memory, and finally the root sequence of the binary tree is output.
Each node of a binary tree is uniquely identified with a different integer, and the following two-tree
The root sequence is 9 5 32 67
Post-root sequence 9 32 67 5
Previous root sequence 5 9 67 32
First reading into a number n means that there are n elements in both the middle order and the post sequence.
Then enter the sequence of the middle sequence in the input sequence.
The output sequence of first order.
Input:
4
9 5 32 67
9 32 67 5
Output:
5 9 67 32
#include <stdio.h> #include <string.h>void build (int len, int *s1, int *s2, int *s) { int p; int i; if (len<=0) return; else{for (i=0; i<len; i++) { if (s1[i]==s2[len-1]) { p = i; } } Build (p, S1, S2, s+1); Build (Len-p-1, s1+p+1, S2+p, s+p+1); S[0] = s2[len-1];} } int main () { int i; int s1[1000], s2[1000], s3[1000]; int n; while (scanf ("%d", &n)!=eof) {for (i=0; i<n; i++) { scanf ("%d", &s1[i]); } for (i=0; i<n; i++) { scanf ("%d", &s2[i]); } Build (n, s1, S2, S3); for (i=0; i<n; i++) { printf ("%d%c", S3[i], i==n-1? ' \ n ': '); } } return 0;}