Input hierarchy traversal, output sequence, preamble, post-order traversal

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.