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

来源:互联网 发布:wto数据库 编辑:程序博客网 时间:2024/06/01 08:12

   计算二叉树的深度时,可以用先分别计算其子树的深度,在通过判断其左右子树深度的大小,大的为其二叉树的深度;二叉树的遍历以及求叶子数详见我的其他同类文章,分类为二叉树。

下面为题目:


下面为具体代码:

#include <stdio.h>#include <stdlib.h>typedef struct node{    char data;    struct node *lchild,*rchild;}node,*nodeptr;char a[55];int i,count;struct node *Creat(struct node *T){    T=(struct node *)malloc(sizeof(struct node));    if(a[i++]==',')T=NULL;    else    {        T->data=a[i-1];        T->lchild=Creat(T->lchild);        T->rchild=Creat(T->rchild);    }    return T;}void ldr(struct node *T){//中序遍历二叉树    if(T)    {        ldr(T->lchild);        printf("%c",T->data);        ldr(T->rchild);    }}void lrd(struct node *T){//后序遍历二叉树    if(T)    {        lrd(T->lchild);        lrd(T->rchild);        printf("%c",T->data);    }}int Countleaf(struct node *T){//统计叶子节点个数    if(T)    {        if((!T->rchild)&&(!T->lchild))        {            count++;        }        Countleaf(T->lchild);        Countleaf(T->rchild);    }    return count;}int depth(struct node *T){    int de,del,der;//de为一个子树的深度    //del为这棵树左子树的深度    //der为这棵树右子树的深度    if(!T)de=0;    else    {        del=depth(T->lchild);        der=depth(T->rchild);        de=1+(del>der?del:der);    }    return de;}int main(){    struct node *T;    while(~scanf("%s",a))    {        i=0;        count=0;        T=Creat(T);        ldr(T);        printf("\n");        lrd(T);        printf("\n");        printf("%d\n",Countleaf(T));        printf("%d\n",depth(T));    }    return 0;}

做一个题目就详细分析一个题目的代码,慢慢也就会觉得递归没有那么难了。关键是多练习,世上无难事,只怕有心人,加油!!

0 0
原创粉丝点击