我是靠谱客的博主 专一天空,这篇文章主要介绍2136 数据结构实验之二叉树的建立与遍历,现在分享给大家,希望可以做个参考。

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

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

cbegdfa
cgefdba
3
5


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
    char data;
    struct node *l,*r;
};
int nu=0;
struct node *build (struct node *t)
{
    char x;
    x=getchar();
    if (x==',')
        t=NULL;
    else
    {
        t=(struct node *)malloc(sizeof (struct node ));
        t->data=x;
        t->l=build(t->l);
        t->r=build(t->r);
    }
    return t;
}
void mid (struct node *t)
{
    if (t!=NULL)
    {
        mid(t->l);
        printf ("%c",t->data);
        mid(t->r);
    }
}
void last (struct node *t)
{
    if (t!=NULL)
    {
        last(t->l);
        last (t->r);
        printf ("%c",t->data);
    }
}
void num (struct node *t)
{
    if (t!=NULL)
    {
        if (t->l==NULL && t->r == NULL)
            nu++;
        else
        {
            num (t->l);
            num (t->r);
        }
    }
}
int depth (struct node *t)
{
    int a=0,b=0;
    if (t!=NULL)
    {
        a=depth(t->l);
        b=depth(t->r);
        if (a>b)
            return a+1;
        else
            return b+1;
    }
    return 0;

}
int main ()
{
    int de;
    struct node *tree= NULL;//创建新的结构体用来存储生成的二叉树
    tree=build(tree);//生成二叉树
    mid (tree);//中序
    printf ("n");
    last (tree);//后序
    printf ("n");
    num (tree);//查找叶子的个数
    printf ("%dn",nu);
    de=depth(tree);//求深度
    printf ("%dn",de);
    return 0;
}
 



最后

以上就是专一天空最近收集整理的关于2136 数据结构实验之二叉树的建立与遍历的全部内容,更多相关2136内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部