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

来源:互联网 发布:淘宝ins是什么意思 编辑:程序博客网 时间:2024/05/10 11:37

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

cbegdfacgefdba35

提示

 

这个题关键点在于求二叉树深度,特别是通过递归函数求二叉树深度时,特别容易被递归过程搞混,大家可以借助这个运行截图来加深理解!这个是单独求二叉树深度的截图!



具体代码如下:
#include<stdio.h>#include<string.h>#include<malloc.h>#include<stdlib.h>#include<math.h>int count;int num;//int ldepth,rdepth;char a[1000];int i;struct node{    char data;    struct node *lc,*rc;};struct node *creat(){    struct node *root;    root=(struct node *)malloc(sizeof(struct node));    char c;    c=a[++i];    if(c==',')    {        return NULL;    }    else    {        root->data=c;        root->lc=creat();        root->rc=creat();    }    return root;};void midput(struct node *root){    if(root!=NULL)    {       midput(root->lc);        printf("%c",root->data);        num++;        if(root->lc==NULL&&root->rc==NULL)        {            count++;        }       midput(root->rc);    }}void lastput(struct node *root){    if(root!=NULL)    {       lastput(root->lc);       lastput(root->rc);        printf("%c",root->data);    }}int depth(struct node *root){    int ldepth,rdepth,t1,t2;    if(root==NULL)    {        printf("\n");        return 0;    }    else    {        ldepth=depth(root->lc);        printf("**%d**\n",ldepth);        rdepth=depth(root->rc);        printf("$$%d$$\n",rdepth);        if(ldepth>rdepth)        {            return ldepth+1;        }        else        {            return rdepth+1;        }    }}int main(){    while(~scanf("%s",&a))    {        struct node *root;        i=-1;        root=creat();        count=0;        num=0;        midput(root);        printf("\n");        lastput(root);        printf("\n");        printf("%d\n",count);        printf("%d\n",depth(root));    }    return 0;}

0 0
原创粉丝点击