数据结构实验之二叉树的建立与遍历

来源:互联网 发布:分类别思维知乎 编辑:程序博客网 时间:2024/05/01 10:40

sdut原题链接
数据结构实验之二叉树的建立与遍历
Time Limit: 1000MS Memory Limit: 65536KB

Problem Description
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。

Input
输入一个长度小于50个字符的字符串。

Output
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。

Example Input
abc,,de,g,,f,,,

Example Output
cbegdfa
cgefdba
3
5

Hint

Author
ma6174

以下为accepted代码

#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{    char date;    struct node *left;    struct node *right;}BinTree;char s[54];int flag, y1, y2;BinTree *root;BinTree * creat()//建树{    BinTree * root;    if(s[flag++] == ',')        root = NULL;    else    {        root = (BinTree *)malloc(sizeof(BinTree));        root->date = s[flag-1];        root->left = creat();        root->right = creat();    }    return root;}void mid(BinTree *root)//中序遍历{    if(root)    {        mid(root->left);        printf("%c", root->date);        mid(root->right);    }}void last(BinTree *root)//后序遍历{    if(root)    {        last(root->left);        last(root->right);        printf("%c", root->date);    }}void leave(BinTree *root)//计算叶子数量{    if(root){        if(root->left == NULL && root->right == NULL)        {            y1++;        }        leave(root->left);        leave(root->right);    }}int get_hight(BinTree *root)//计算树的高度{    int HL, HR, MAXH;    if(root){        HL = get_hight(root->left);        HR = get_hight(root->right);        MAXH = HL > HR? HL: HR;        return (MAXH + 1);    }    else        return 0;}int main(){    scanf("%s", s);    flag = y1 = y2 = 0;//初始化    root = creat();//调用建树函数    mid(root);//调用中序遍历函数    printf("\n");    last(root);//调用后序遍历函数    printf("\n");    leave(root);//调用计算叶子数量函数    y2 = get_hight(root);//调用计算树的高度函数    printf("%d\n", y1);    printf("%d\n", y2);    return 0;}/***************************************************User name: Result: AcceptedTake time: 0msTake Memory: 112KBSubmit time: 2017-02-07 11:08:24****************************************************/
0 0
原创粉丝点击