二叉树创建及功能函数

4 篇文章 0 订阅
1 篇文章 0 订阅
#ifndef _BI_NODE_
#define _BI_NODE_

typedef struct _binode {
	char data;
	struct _binode *lchild, *rchild;
}BiNode;

#endif // !_BI_NODE_
#ifndef _TREE_OP_
#define _TREE_OP_

void createBiTree(BiNode **T);
void preorderTraverse(BiNode *T);
void InorderTraverse(BiNode *T);
void postorderTraverse(BiNode *T);
int LeafCount(BiNode *T);
int Hight(BiNode *T);

#endif // !_TREE_OP_

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

//前序创建二叉树
void createBiTree(BiNode **T) {	//这里用了指针的指针,如果只用一维指针的话,则无法创建
	char ch;
	scanf("%c", &ch);
	if (ch == '#') {
		*T = NULL;
	}
	else {
		*T = (BiNode *)malloc(sizeof(BiNode));
		(*T)->data = ch;
		createBiTree(&((*T)->lchild));
		createBiTree(&((*T)->rchild));
	}
}

//前序遍历
void preorderTraverse(BiNode *T) {
	if (T) {
		printf("%c", T->data);
		preorderTraverse(T->lchild);
		preorderTraverse(T->rchild);
	}
}

//中序遍历
void InorderTraverse(BiNode *T) {
	if (T) {
		InorderTraverse(T->lchild);
		printf("%c", T->data);
		InorderTraverse(T->rchild);
	}
}

//后序遍历
void postorderTraverse(BiNode *T) {
	if (T) {
		postorderTraverse(T->lchild);
		postorderTraverse(T->rchild);
		printf("%c", T->data);
	}
}

//求叶子节点
int LeafCount(BiNode *T) {
	static int count = 0;	//注意此处的静态本地变量
	if (T) {
		if (!(T->lchild) && !(T->rchild)) {
			printf("%c", T->data);
			count += 1;
		}
		LeafCount(T->lchild);
		LeafCount(T->rchild);
	}
	return count;
}

//求树高
int Hight(BiNode *T) {
	int hight = 0;
	int lh, rh;
	if (T) {
		lh = Hight(T->lchild);
		rh = Hight(T->rchild);
		hight = (lh > rh) ? lh : rh;
		return hight + 1;
	}
	else {
		return 0;
	}
}

#include <stdio.h>
#include <stdlib.h>
#include "BiNode.h"
#include "TreeOp.h"

//测试函数
int main()
{
	BiNode *t;
	createBiTree(&t);
	
	printf("前序遍历\n");
	preorderTraverse(t);
	
	printf("\n");
	printf("中序遍历\n");
	InorderTraverse(t);
	
	printf("\n");
	printf("后序遍历\n");
	postorderTraverse(t);
	
	printf("\n");
	printf("叶子节点数:%d\n", LeafCount(t));
	
	printf("\n");
	printf("树高:%d\n", Hight(t));

	return 0;
}



  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值