码迷,mamicode.com
首页 > 编程语言 > 详细

C语言实现二叉查找树

时间:2015-09-13 23:12:18      阅读:461      评论:0      收藏:0      [点我收藏+]

标签:

#include<stdio.h>
#include<stdlib.h>
/*
* 数据结构:二叉查找树,即左孩子<父节点<右孩子
* C语言实现
* 2015-9-13
*/
typedef struct TreeNode *PtrToNode;
typedef PtrToNode Tree;
typedef PtrToNode Position;
struct TreeNode {
	int Element;
	Tree Left; //节点左孩子
	Tree Right; //节点右孩子
};
/*
* 使二叉树变为空,采用递归释放内存的方法
*/
Tree MakeEmpty(Tree T)
{
	if (T != NULL) {
		MakeEmpty(T->Left);
		MakeEmpty(T->Right);
		free(T);
	}
	return NULL;
}
/*
* 查找某一元素
*/
Position Find(int X, Tree T)
{
	if (T == NULL) {
		return NULL;
	}
	if (X < T->Element) {
		return Find(X, T->Left);
	}
	else if (X>T->Element) {
		return Find(X, T->Right);
	}
	else {
		return T;
	}
}
/*
* 寻找最小值
*/
Position FindMin(Tree T)
{
	if (T == NULL) {
		return NULL;
	}
	else if (T->Left == NULL) {
		return T;
	}
	else {
		FindMin(T->Left);
	}
}
/*
* 寻找最大值
*/
Position FindMax(Tree T)
{
	if (T == NULL) {
		return NULL;
	}
	else if (T->Right == NULL) {
		return T;
	}
	else {
		FindMax(T->Right);
	}
}
/*
* 插入元素到二叉树中
*/
Tree Insert(int X, Tree T)
{
	if (T == NULL) {
		T = (Tree)malloc(sizeof(struct TreeNode));
		if (T == NULL) {
			printf("Out of memory!\n");
			exit(1);
		}
		else {
			T->Element = X;
			T->Left = T->Right = NULL;
		}
	}
	else if (X < T->Element) {
		T->Left = Insert(X, T->Left);
	}
	else if (X > T->Element) {
		T->Right = Insert(X, T->Right);
	}
	return T;
}
/*
* 删除树中的某个元素
*/
Tree Delete(int X, Tree T)
{
	Position TmpCell;
	if (T == NULL) {
		printf("No such element!\n");
		exit(2);
	}
	else if (X < T->Element) {
		T->Left = Delete(X, T->Left);
	}
	else if (X > T->Element) {
		T->Right = Delete(X, T->Right);
	}
	else if (T->Left && T->Right) {
		TmpCell = FindMin(T->Right);
		T->Element = TmpCell->Element;
		T->Right = Delete(T->Element, T->Right);
	}
	else {
		TmpCell = T;
		if (T->Left == NULL) {
			T = T->Right;
		}
		else if (T->Right == NULL) {
			T = T->Left;
		}
		free(TmpCell);
	}
}
/*
* 前序遍历打印所有元素
*/
void PrintWithPreorder(Tree T)
{
	if (T != NULL) {
		printf("%d\t", T->Element);
		PrintWithPreorder(T->Left);
		PrintWithPreorder(T->Right);
	}
}
/*
* 中序遍历打印所有元素
*/
void PrintWithInorder(Tree T)
{
	if (T != NULL) {
		PrintWithInorder(T->Left);
		printf("%d\t", T->Element);
		PrintWithInorder(T->Right);
	}
}
/*
* 后序遍历打印所有元素
*/
void PrintWithPostorder(Tree T)
{
	if (T != NULL) {
		PrintWithPostorder(T->Left);
		PrintWithPostorder(T->Right);
		printf("%d\t", T->Element);
	}
}

/*
* 测试程序
*/
int main()
{
	Tree T = NULL;
	T = Insert(1, T);
	T = Insert(0, T);
	T = Insert(-1, T);
	T = Insert(20, T);
	T = Insert(-10, T);
	T = Insert(10, T);
	T = Insert(2, T);
	T = Insert(5, T);
	printf("Min is %d\n", FindMin(T)->Element);
	printf("Max is %d\n", FindMax(T)->Element);
	//下面采用中序遍历方式打印所有节点元素
	PrintWithInorder(T);
	return 0;
}

本博文持续更新...

C语言实现二叉查找树

标签:

原文地址:http://my.oschina.net/zzw922cn/blog/505650

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!