Experiment of 3341 data structure: binary tree two: traversing binary tree

Experiment of 3341 data structure: binary tree two: traversing binary tree

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

It is known that a binary tree traverses the input character sequence in order, such as ABC, De, G, F,, (where, represents an empty node). Please build a binary tree and traverse it in the middle and back order.

Input

Continuous input of multiple groups of data, each group of data input a string less than 50 characters in length.

Output

Each group of input data corresponds to two lines of output:
The first line outputs the middle order traversal sequence;
Line 2 outputs the sequence of traversal.

 

Example Input

abc,,de,g,,f,,,

Example Output

cbegdfacgefdba

#include <stdio.h>  
#include <string.h>  
#include <stdlib.h>  
  
  
struct node  
{  
  
  
    char data;  
    struct node *l,*r;  
};  
char st[51];  
int cnt;  
struct node *creat()                                     //Here is the preservation of the tree traversed in order  
{  
    struct node *root;  
    if(st[++cnt]==',')  
    {  
        root=NULL;  
    }  
    else  
    {  
        root = (struct node *)malloc(sizeof(struct node));  
        root->data = st[cnt];  
        root->l = creat();  
        root->r = creat();  
    }  
    return root;  
}  
void zhongxu(struct node *root)          //Middle order ergodic  
{  
    if(root)  
    {  
        zhongxu(root->l);  
        printf("%c",root->data);  
        zhongxu(root->r);  
    }  
}  
void houxu(struct node *root)               //Postorder ergodic  
{  
    if(root)  
    {  
        houxu(root->l);  
        houxu(root->r);  
        printf("%c",root->data);  
    }  
}  
int main()  
{  
    while(~scanf("%s",st))  
    {  
        cnt = -1;  
        struct node *root;  
        root = creat();  
        zhongxu(root);  
        printf("\n");  
        houxu(root);  
        printf("\n");  
    }  
    return 0;  
}  

Tags: less

Posted on Tue, 05 May 2020 00:51:14 -0400 by asunsha