二叉樹創建及功能函數

#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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章