二叉树day1

二叉树day1

代码:

  • 二叉树的创建
  • 二叉树的前序遍历 中序遍历 后序遍历 层序遍历
  • 二叉树叶子结点和深度的计算
#include <stdio.h>
#include <stdlib.h>
char s[55];
int i, len, num, sum;
struct tree
{
    char data;
    struct tree *Lchild;
    struct tree *Rchild;
};

struct tree * creat()
{
    struct tree *root;
    if(s[++i]!=',')
    {
    root = (struct tree *)malloc(sizeof(struct tree));
    root -> data = s[i];
    root -> Lchild = creat();
    root -> Rchild = creat();
    if(root -> Rchild==NULL&&root -> Lchild==NULL)//判断叶子节点数
    {
        num++;
    }
    }else
    {
        root = NULL;
    }
    return root;
}

void inshow(struct tree *t)//中序遍历
{
    if(t!=NULL)
    {
        inshow(t->Lchild);
        printf("%c", t->data);
        inshow(t->Rchild);
    }
}

void postshow(struct tree *t)//后序遍历
{
    if(t!=NULL)
    {
        postshow(t->Lchild);
        postshow(t->Rchild);
        printf("%c", t->data);
    }
}

void show(struct tree *t)//前序遍历
{
    if(t!=NULL)
    {
        show(t->Lchild);
        show(t->Rchild);
        printf("%c", t->data);
    }
}

int depth(struct tree *t)
{
    int l, r;
    if(t==NULL)
    {
        return 0;
    }
    else
    {
        l = depth(t->Lchild);
        r = depth(t->Rchild);
        return l>r?l+1:r+1;
    }
}

void levelshow(struct tree *head)
{
    struct tree *temp[150];
    int front=0, rear=0;
    temp[rear++] = head;
    while(front<rear)
    {
     if(temp[front])
     {
         printf("%c", temp[front]->data);
         temp[rear++] = temp[front]->Lchild;
         temp[rear++] = temp[front]->Rchild;
     }
     front++;
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    getchar();
    while(n--)
    {
    gets(s);
    len = strlen(s);
    struct tree *head;
    i = -1, num = 0;
    head = creat();
    inshow(head);//中序遍历
    printf("\n");
    postshow(head);//后序遍历
    printf("\n");
    show(head); //前序遍历
    printf("\n");
    levelshow(head);//层序遍历
    printf("\n");
    printf("%d\n", num);//叶子结点数
    printf("%d\n", depth(head));//深度
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值