Binary Tree traversals
Time limit:1000 ms
Memory limit:32768kb
64bit Io format:% I64d & % i64usubmit status
Description
A binary tree is a finite set of vertices that is either empty or consists of a root R and two disjoint Binary Trees called the Left and Right Subtrees. there are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. they are preorder, inorder and postorder. let t be a binary tree with root R and Subtrees T1, T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root R, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit R.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
Input
The input contains several test cases. the first line of each test case contains a single integer N (1 <= n <= 1000), the number of vertices of the binary tree. followed by two lines, respectively indicating the preorder sequence and inorder sequence. you can assume they are always correspond to a exclusive binary tree.
Output
For each test case print a single line specifying the corresponding postorder sequence.
Sample Input
91 2 4 7 3 5 8 9 64 7 2 1 8 5 9 3 6
Sample output
7 4 2 8 9 5 6 3 1 I don't know why I couldn't run the string address in the function. I couldn't find the error after searching for a long time! This is the error code:
# Include <stdio. h> # include <string. h> int N; int A [1000], B [1000], C [1000]; void build (INT Len, int S1, int S2, int s) {int P; int I; If (LEN <= 0) return; else {for (I = S2; I <S2 + Len; I ++) {If (B [I] = A [S1]) {P = I; break;} C [S + len-1] = A [S1]; build (p, s1 + 1, S2, S); // The left build (len-p-1, S1 + p + 1, S2 + p + 1, S + p ); // right} int main () {int I, j; while (scanf ("% d", & N )! = EOF) {for (I = 0; I <n; I ++) {scanf ("% d", & A [I]) ;}for (I = 0; I <n; I ++) {scanf ("% d", & B [I]);} build (n, 0, 0, 0 ); for (I = 0; I <n; I ++) {printf ("* % d", C [I]) ;}} return 0 ;}
This is the correct code:
#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(s2[i]==s1[0]) { p = i; } } build(p, s1+1, s2, s); build(len-p-1, s1+p+1, s2+p+1, s+p); s[len-1] = s1[0]; } } 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;}