二叉树的简单操作(C语言实现)

//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;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值