链式二叉树的实现

二叉树可以使用顺序结构,或者链式结构来 实现这里给出一个链式结构的实现例子

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Status;	//函数类型的状态
typedef char TElemType;
char EMPTY_NODE = ' ';//空结点

typedef struct Node{
	TElemType data;//数据
	//左右孩子指针
	struct Node *lchild;
	struct Node *rchild;
}BiNode,*BiTree;

//构造空二叉树T
Status InitBiTree(BiTree *T){
	*T = NULL;
	return OK;
}

//判断是否为空树
Status BiTreeEmpty(BiTree T){
	if(T){
		return FALSE;
	} else {
		return TRUE;
	}
}
//销毁二叉树
void DestroyBiTree(BiTree *T){
	if(*T == NULL){
		return;
	}
	//非空进入销毁流程
	//采用后续遍历的方式销毁二叉树
	DestroyBiTree(&(*T)->lchild);
	DestroyBiTree(&(*T)->rchild);
	free(*T);
	*T = NULL;
}


//使用指定字符串构造空数
//#表示空结点
char *str = "ABDH##K##E##CFI###G#J##";
int strIndex = 0;
void CreateBiTree(BiTree *T)
{ 
	TElemType ch;
	//不用判断字符尾,因为不符合接下来的条件的字符将会略过
	ch = str[strIndex++];
	
	if(ch == '#'){
		*T = NULL;
	} else {
		*T = (BiNode*)malloc(sizeof(BiNode));
		if(!*T){
			printf("CreateBiTree malloc fail!\n");
			exit(EXIT_FAILURE);
		}
		//前序遍历生成树
		(*T)->data = ch;
		CreateBiTree(&(*T)->lchild);
		CreateBiTree(&(*T)->rchild);
	}
}

int BiTreeDepth(BiTree T){
	if(BiTreeEmpty(T)){
		return 0;//空树
	}
	//使用递归解决:当前树的深度等于左右子树中最深的一个+1
	int lDepth;
	int rDepth;
	
	if(T->lchild){
		lDepth = BiTreeDepth(T->lchild)+1;
	} else {
		lDepth = 1;
	}

	if(T->rchild){
		rDepth = BiTreeDepth(T->rchild)+1;
	} else {
		rDepth = 1;
	}
	return lDepth > rDepth ? lDepth : rDepth;
}

TElemType Root(BiTree T){
	if(BiTreeEmpty(T)){
		return EMPTY_NODE;//空树
	} else {
		return T->data;
	}
}

TElemType Value(BiTree T)
{
	return T->data;
}

// 前序遍历
void PreOrderTraverse(BiTree T){
	if(T == NULL){
		return;
	}
	printf("%c\n",T->data);
	PreOrderTraverse(T->lchild);
	PreOrderTraverse(T->rchild);
}

// 中序遍历
void InOrderTraverse(BiTree T){
	if(T == NULL){
		return;
	}
	
	InOrderTraverse(T->lchild);
	printf("%c\n",T->data);
	InOrderTraverse(T->rchild);
}

// 后序遍历
void PostOrderTraverse(BiTree T){
	if(T == NULL){
		return;
	}
	
	PostOrderTraverse(T->lchild);
	PostOrderTraverse(T->rchild);
	printf("%c\n",T->data);
}

int main(){
	BiTree tree;
	InitBiTree(&tree);
	//printf("Empty:%d\n",BiTreeEmpty(tree));
	CreateBiTree(&tree);
	printf("Empty:%d\n",BiTreeEmpty(tree));
	PreOrderTraverse(tree);
	printf("Depth:%d\n",BiTreeDepth(tree));
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值