Title Description
Input a complete binary tree hierarchy traversal sequence, output the complete binary tree of the middle sequence traversal sequence.
For example, the following two-fork tree has a hierarchical traversal sequence of "ABCDE" and a middle-order traversal of "DBEAC".
A
/ \
B C
/ \
D E
There is no need to say more about recursive notation, and before, in and after, all are one law;
It is important to see how to build a binary tree, and listen to decomposition;
Input hierarchy traversal output in sequence
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define _oj_
typedef struct TREE1
{
char data;
struct TREE1 *lchild;
struct TREE1 *rchild;
} tree1, *tree;
Tree
Creat_tree (Tree T, char *str, int i, int len)
{
if (2 * i <= len) {
Tree T1, T2;
if ((2 * i) <= len) {//left son
T1 = (tree) malloc (sizeof (TREE1));
T1->data = str[2 * I];
T->lchild = T1;
T->lchild = Creat_tree (T->lchild, str, 2 * i, Len);
}
if ((2 * i + 1) <= len) {//Right son
T2 = (tree) malloc (sizeof (TREE1));
T2->data = str[2 * i + 1];
T->rchild = T2;
T->rchild = Creat_tree (T->rchild, str, 2 * i + 1, len);
}
}
else//if the incoming value is greater than Len, then he is the leaf node.
T->lchild = T->rchild = NULL;
return T;
}
void
Pre_oder (Tree T)
{
if (T! = NULL)
{
Pre_oder (T->lchild);
printf ("%c", t->data);
Pre_oder (T->rchild);
}
}
int main (int argc, char const *argv[]) {
#ifndef _oj_//online_judge
Freopen ("Input.txt", "R", stdin);
#endif
Tree T;
int i = 0, len = 0;
Char str[100];
scanf ("%s", str);
len = strlen (str);//Use arrays to store complete binary trees then the left son is 2i and the right son is 2i+1;
for (i = len;i >= 0; i--)
Str[i + 1] = str[i];//0 Okay, start with the number one.
T = (tree) malloc (sizeof (TREE1)); T->data = str[1];
t = creat_tree (t, str, 1, Len);
Pre_oder (T);
printf ("\ n");
return 0;
}
Input hierarchy traversal, output sequence, preamble, post-order traversal