国庆day3 二叉树

头文件

#ifndef __BTREE_H__
#define __BTREE_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
	char data;
	struct node *lchild;
	struct node *rchild;
}node, *node_p;
 
node_p create_node(char data);
node_p create_btree();
void pri_show(node_p T);
void ino_show(node_p T);
void pos_show(node_p T);
void destroyTree(node_p T);
#endif

功能函数

#include "btree.h"
//创建节点(node)
node_p create_node(char data)
{
	node_p ne = (node_p)malloc(sizeof(node));
	if(ne == NULL)
	{
		printf("入参为空");
		return NULL;
	}
	ne -> data = data;
 
	return ne;
}
 
//创建二叉树(btree)
node_p create_btree()
{
	char data = '\0';
	scanf(" %c",&data);
	if(data == '#')
		return NULL;
	node_p ne = create_node(data);
	ne -> lchild = create_btree();
	ne -> rchild = create_btree();
	return ne;
}
//二叉树的先序遍历
void pri_show(node_p T)
{
	if(T == NULL)
		return;
 
	printf("%c",T -> data);
	pri_show(T -> lchild);
	pri_show(T -> rchild);
 
}
 
//二叉树的中序遍历
void ino_show(node_p T)
{
	if(T == NULL)
		return;
	ino_show(T -> lchild);
	printf("%c", T -> data);
	ino_show(T -> rchild);
 
}
 
//二叉树的后续遍历
void pos_show(node_p T)
{
	if(T == NULL)
		return;
	pos_show(T -> lchild);
	pos_show(T -> rchild);
	printf("%c", T -> data);
 
}

//销毁二叉树
void destroyTree(node_p T){
    if (T == NULL) {
        return;
    }
    // 递归销毁左子树
    destroyTree(T -> lchild);
    // 递归销毁右子树
    destroyTree(T -> rchild);
    // 释放当前节点的内存
    free(T);
}

主函数

#include "btree.h"
 
int main()
{
	node_p T = create_btree();
	pri_show(T);
	putchar(10);
	ino_show(T);
	putchar(10);
	pos_show(T);
	putchar(10);
	destroyTree(T);	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值