暑假集训day7——数据结构实验之二叉树的建立与遍历(求深度为什么要最后加1?)

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

 

Input

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

Output

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

Sample Input

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

Sample Output

cbegdfa
cgefdba
3
5

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char s[100];
int ans, top, x;

struct node
{
    char data;
    struct node *l, *r;

};

struct node *creat()
{
    struct node *root;

    if(s[++top] == ',')
    {
        root = NULL;
    }

    else
    {
        root = (struct node *)malloc(sizeof(struct node));
        root-> data = s[top];

        root-> l = creat();
        root-> r = creat();
    }

    return root;
}

void mid(struct node *root)
{
    if(root)
    {
        mid(root-> l);
        printf("%c", root-> data);
        mid(root-> r);
    }
}

void hou(struct node *root)
{
    if(root)
    {
        hou(root-> l);
        hou(root-> r);

        printf("%c", root-> data);
    }
}

int jiedian(struct node *root)
{
    if(root)
    {
        if(root-> l == NULL && root-> r == NULL)
        {
            ans++;
        }

        else
        {
            jiedian(root-> l);
            jiedian(root-> r);
        }
    }

    return ans;
}

int shendu(struct node *root)
{
    int l1, l2;

    if(!root)
    {
        return 0;
    }


    l1 = shendu(root-> l);
    l2 = shendu(root-> r);


    return l1 > l2 ?l1 + 1:l2 + 1;
}

int main(void)
{
    struct node *root;

    gets(s);
    top = -1;
    ans = 0;
    x = 0;

    root = creat();
    mid(root);
    printf("\n");

    hou(root);
    printf("\n");

    jiedian(root);
    printf("%d\n", ans);

    x = shendu(root);
    printf("%d\n", x);


    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/Eider1998/article/details/81477293