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

 题目链接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2136

  这个题看书+问学长.2A.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int num=-1;
char str[51];
struct tree
{
    char  lat;
    struct tree *left;
    struct tree *right;
};
struct tree *build()//建树
{
    struct tree *p;
    num++;
    if(str[num]==',')
    return NULL;
    p = (struct tree *)malloc(sizeof(struct tree));
    p -> lat = str[num];
    p -> left = build();
    p -> right = build();
    return p;
}
void  midshow(struct tree *k)//中序
{
   if(k)
   {
       midshow(k -> left);
       printf("%c",k -> lat);
       midshow(k -> right);
   }
   else return ;
}
void downshow(struct tree *k)//后序
{
    if(k)
    {
        downshow(k -> left);
        downshow(k -> right);
        printf("%c",k -> lat);
    }
}
int count(struct tree *k)//记录叶子节点
{
    if(k)
    {
     if(k -> right == NULL && k -> left == NULL)
     return 1;
     else
     {
         return count(k -> right)+count(k -> left);
     }
    }
    else
    return 0;
}
int depth(struct tree *k)//记录深度
{
    int m,n;
    if(k == NULL)
    return 0;
    else
    {
        m = depth(k -> left);
        n = depth(k -> right);
        if(m > n)
        return m+1;
        else
        return n+1;
    }
}
int main()
{
    struct tree *head;
    int i,j;
    scanf("%s",str);
    head = build();
    midshow (head);
    printf("\n");
    downshow (head);
    printf("\n");
    i = count(head);
    printf("%d\n",i);
    j = depth(head);
    printf("%d\n",j);
    return 0;
}

 

转载于:https://www.cnblogs.com/naix-x/archive/2012/05/28/2521564.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值