//bintree.h
#ifndef _BINTREE_H_
#define _BINTREE_H_
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#include<assert.h>
#pragma warning(disable:4996)
typedef char ElemType;
typedef struct BintreeNode
{
ElemType val;
struct BintreeNode* leftchild;
struct BintreeNode* rightchild;
}BinNode;
typedef BinNode* Bintree;
void BintreeInit(Bintree* t);
void BintreeCreate(Bintree* t);
int size(Bintree t);
int height(Bintree t);
void printVLR(Bintree t);//先序输出
void BintreeDestory(Bintree* t);
//###############################################################
void BintreeInit(Bintree* t)//初始化
{
(*t) = NULL;
}
void BintreeCreate(Bintree* t)//二叉树的创建
{
assert(t);
ElemType item;
scanf("%c", &item);
if (item == '#'){
(*t) = NULL;
}
else{
(*t) = (BinNode*)malloc(sizeof(BinNode));
(*t)->val = item;
BintreeCreate(&(*t)->leftchild);
BintreeCreate(&(*t)->rightchild);
}
}
int size(Bintree t)//二叉树结点的个数
{
if (t == NULL){
return 0;
}
else{
return size(t->leftchild) + size(t->rightchild) + 1;
}
}
void printVLR(Bintree t)//先序输出
{
if (t != NULL){
printf("%c ", t->val);
printVLR(t->leftchild);
printVLR(t->rightchild);
}
}
int height(Bintree t)
{
if (t == NULL)
{
return 0;
}
else{
int left_h = height(t->leftchild);
int right_h = height(t->rightchild);
return (left_h > right_h ? left_h : right_h) + 1;
}
}
void BintreeDestory(Bintree* t)
{
assert(t);
BinNode *p = *t;
if (p != NULL){
if (p->leftchild){
BintreeDestory(&(p->leftchild));
p->leftchild = NULL;
}
if (p->rightchild){
BintreeDestory(&(p->rightchild));
p->rightchild = NULL;
}
if (p == NULL){
free(p);
p = NULL;
}
}
if ((*t)->leftchild == NULL && (*t)->rightchild == NULL){
free(p);
p = NULL;
}
}
#endif _BINTREE_H_
//bintree.c
#include"bintree.h"
int main()
{
BinNode* t;
BintreeInit(&t);
BintreeCreate(&t);
printf("size = %d\n", size(t));
printVLR(t);
printf("\n");
printf("height = %d\n", height(t));
BintreeDestory(&t);
system("pause");
return 0;
}
二叉树的简单操作(C语言实现)
最新推荐文章于 2022-12-15 18:37:25 发布