数据结构(C语言):二叉树的创建、遍历、销毁等操作

tree.h

#ifndef _TREE_H_
#define _TREE_H_

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

typedef struct node
{
	char data;
	struct node *pL;
	struct node *pR;
}BTNode;


extern BTNode *createBinTree();
extern void preOrder(BTNode *pRoot);
extern void inOrder(BTNode *pRoot);
extern void laOrder(BTNode *pRoot);
extern int getNodeNum(BTNode *pRoot);
extern void destroyTree(BTNode *pRoot);


#endif

tree.c

#include "tree.h"

int idx = 0;
char tree[] = {"ABDG###E#H##CF###"};//先序

/*创建二叉树*/
BTNode *createBinTree()
{
	BTNode *pNode = NULL;
	char ch = tree[idx++];
	if(ch == '#')
	{
		return NULL;
	}
	else
	{
		pNode = malloc(sizeof(BTNode));
		if(NULL == pNode)
		{
			perror("fail to createBinTree malloc!\n");
			return NULL;
		}
		pNode->data = ch;
		pNode->pL = createBinTree();
		pNode->pR = createBinTree();
	}

	return pNode;
}

/*前序遍历*/
void preOrder(BTNode *pRoot)
{
	if(NULL == pRoot)
	{
		return;
	}
	printf("%c",pRoot->data);
	fflush(stdout);
	preOrder(pRoot->pL);
	preOrder(pRoot->pR);
}

/*中序遍历*/
void inOrder(BTNode *pRoot)
{
	if(NULL == pRoot)
	{
		return;
	}
	inOrder(pRoot->pL);
	printf("%c",pRoot->data);
	inOrder(pRoot->pR);
}

/*后续遍历*/
void laOrder(BTNode *pRoot)
{
	if(NULL == pRoot)
	{
		return;
	}
	laOrder(pRoot->pL);
	laOrder(pRoot->pR);
	printf("%c",pRoot->data);
}

/*获取结点数*/
int getNodeNum(BTNode *pRoot)
{
	if(NULL == pRoot)
	{
		return 0;
	}
	static int num = 0;
	getNodeNum(pRoot->pL);
	getNodeNum(pRoot->pR);
	num++;
	
	return num;
}

/*二叉树的销毁*/
void destroyTree(BTNode *pRoot)
{
	if(NULL == pRoot)
	{
		return;
	}
	destroyTree(pRoot->pL);
	destroyTree(pRoot->pR);
	free(pRoot);
}

main.c

#include "tree.h"

int main(int argc, const char *argv[])
{
	BTNode *pRoot = NULL;
	pRoot = createBinTree();

	preOrder(pRoot);
	printf("\n");
	inOrder(pRoot);
	printf("\n");
	laOrder(pRoot);
	printf("\n");

	printf("%d\n",getNodeNum(pRoot));
	destroyTree(pRoot);

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值