2024.7.24 作业

二叉树

代码:

/*******************************************/

文件名:BT.c

功能:函数内容

/*******************************************/

#ifndef BT_H
#define BT_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char datatype;
typedef struct Node
{
    datatype data;      //数据域
    struct Node *left;  //左孩子
    struct Node *right; //右孩子
} Node, *BTPtr;
//创建二叉树
BTPtr tree_create();
//先序遍历
void prio_seek(BTPtr B);
//中序遍历
void in_seek(BTPtr B);
//后序遍历
void tail_seek(BTPtr B);
#endif

/*******************************************/

文件名:BT.h

功能:函数声明

/*******************************************/

#include "BT.h"
//创建二叉树
BTPtr tree_create()
{
    char data = 0;
    scanf(" %c", &data);
    if (data == '#')
    {
        return NULL;
    }
    BTPtr p = (BTPtr)malloc(sizeof(Node));
    if (NULL == p)
    {
        printf("节点申请失败\n");
        return NULL;
    }
    p->data = data;
    p->left = tree_create();
    p->right = tree_create();
    return p;
}
//先序遍历
void prio_seek(BTPtr B)
{
    if (NULL == B)
    {
        return;
    }
    printf(" %c\t", B->data);
    prio_seek(B->left);
    prio_seek(B->right);
}
//中序遍历
void in_seek(BTPtr B)
{
    if (NULL == B)
    {
        return;
    }
    prio_seek(B->left);
    printf(" %c\t", B->data);
    prio_seek(B->right);
}
//后序遍历
void tail_seek(BTPtr B)
{
    if (NULL == B)
    {
        return;
    }
    prio_seek(B->left);
    prio_seek(B->right);
    printf(" %c\t", B->data);
}

/*******************************************/

文件名:main.c

功能:函数内容

/*******************************************/

#include "BT.h"
int main(int argc, char const *argv[])
{
    BTPtr B = tree_create();
    if (NULL == B)
    {
        printf("创建失败\n");
        return -1;
    }
    printf("创建成功\n");
    printf("先序遍历结果为:");
    prio_seek(B);
    printf("\n");
    printf("中序遍历结果为:");
    in_seek(B);
    printf("\n");
    printf("后序遍历结果为:");
    tail_seek(B);
    printf("\n");
    return 0;
}

结果:

思维导图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值