二叉树 (求叶子结点&深度)

来源:互联网 发布:韩国人眼中的美女知乎 编辑:程序博客网 时间:2024/04/30 02:51

题目描述
       已知一个按先序序列输入的字符序列,如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 *left;struct node *right;};struct node *make()//建树{    char c;    struct node *str;    c = getchar();    if(c == ',')        str = NULL;    else    {        str=(struct node *)malloc(sizeof(struct node));        str->data = c;        str->left = make();        str->right = make();    }    return str;}void mid(struct node *mid1)//中序{    if(mid1!=NULL)    {        mid(mid1->left);        printf("%c",mid1->data);         mid(mid1->right);    }    else        return ;}void last(struct node *last1)//后序{    if(last1!= NULL)    {        last(last1->left);        last(last1->right);        printf("%c",last1->data);    }    else        return ;}int count = 0;void leaf(struct node *t)//叶子结点数{    if(t!=NULL )    {        if(t->left==NULL && t->right==NULL)      {      count ++;       }        leaf(t->left);        leaf(t->right);    }}int shendu(struct node *t)//深度{    int a = 0;    int b = 0;    if(t!=NULL)    {        a = shendu(t->left);        b = shendu(t->right);        if(a > b)            return a + 1;  //层层累加过程,直到root结点        else         return  b + 1;    }    else        return 0;}int main(){  struct node *t;  t = make();  mid(t);  printf("\n");  last(t);  printf("\n");  leaf(t);printf("%d\n",count);count = 0;int du = shendu(t);  printf("%d\n",du);  return 0;}


 

0 0
原创粉丝点击