Binary Tree Reconstruction, binary tree
For a binary tree T, we can recursively define its first-order traversal, middle-order traversal, and post-order traversal: Faster Traversal
1. PreOrder traversal (PreOrder (T) = T root node + PreOrder (T left subtree) + PreOrder (T right subtree ))
2. In-order traversal (InOrder (T) = InOrder (T's left subtree) + T's root node + InOrder (T's right subtree ))
3. Post-order traversal (PostOrder (T) = PostOrder (left subtree of T) + PostOrder (right subtree of T) + root node of T)
The plus sign indicates the string join operation. For example, in a binary tree, the first traversal is dbacepidermal, and the middle traversal is ABCDEFG.
(The painting is ugly. Do not abandon it)
Requirement: input the first and middle traversal of a tree, and output the second traversal.
Sample input:
Dbacepidermal ABCDEFG
BCAD CBAD
Sample output:
ACBFGED
CDAB
Code:
# Include <stdio. h> # include <string. h> # define MAXN 1000 + 10 void build (int n, char * s1, char * s2, char * s) {if (n <= 0) return; int p = strchr (s2, s1 [0])-s2; // locate the position of the root node in the middle-order traversal build (p, s1 + 1, s2, s ); // recursively construct the descending order traversal build of the Left subtree (n-p-1, s1 + p + 1, s2 + p + 1, s + p ); // construct the back-order traversal of the right subtree. s [n-1] = s1 [0];} int main () {char s1 [MAXN], s2 [MAXN], ans [MAXN]; while (scanf ("% s", s1, s2) = 2) {int nLen = strlen (s1); build (nLen, s1, s2, ans); ans [nLen] = '\ 0'; puts (ans);} return 0 ;}
Through this example, I believe I have a certain understanding of the Traversal method with Binary Trees.
Portal: Binary Tree hierarchy Traversal