数据结构-二叉查找树

树:树是一个大部分操作的运行时间平均为O(log n)的一种数据结构。

    树的递归定义为:一棵树是一些节点的集合。这些集合可以是空集;若为非空,则一棵树由称作根的节点r以及0个或多个非空的(子)树T1、T2、T3、...、Tk组成。这些子树中每一棵的根都被来自根r的一天有向边所连接(可以发现一棵树是N个节点和N-1条边的集合)。

    树叶:没有儿子的节点;

    兄弟:具有相同父亲的节点;

    节点ni的深度:从根到ni的惟一路径长。根的深度为0,树的深度为最深的树叶的深度;

    节点ni的高度:从ni到一片树叶的最长路径的长。所有树叶的高度为0,树的高度为根的高度。

二叉树:是一棵树,其中每个节点都不能有多于两个的儿子。(平均深度为√N)

二叉查找树(BST):树中的每个节点x,它的左子树中所有关键字值小于x的关键字值,而它的右子树中所有关键字值大于x的关键字值.

    下面给出二叉查找树的声明:

struct treeNode;
typedef struct treeNode* position;
typedef struct treeNode* searchTree;

position Find(int x, searchTree t);
position FindMin(searchTree t);
position FindMax(searchTree t);
searchTree Delete(int x, searchTree t);
searchTree Insert(int x, searchTree t);
//searchTree BuildTree(int* a, int n, searchTree t);
void PrintTree(searchTree t);

struct treeNode
{
	int element;
	searchTree left;
	searchTree right;
};
Find例程的实现:

position Find(int x, searchTree t){
	if (t==NULL)
	{
		return NULL;
	}
	else if (x<t->element)
	{
		return Find(x,t->left);
	}
	else if (x>t->element)
	{
		return Find(x, t->right);
	}
	else
	{
		return t;
	}
}

其中注意测试的顺序是:先是树是否为空树进行测试,否则可能在NULL指针上面兜圈子,其余的测试应该是使最不可能的情况安排在最后进行。

FindMin例程的实现:

position FindMin(searchTree t){
	if (t == NULL)
	{
		return NULL;
	}
	else if (t->left==NULL)
	{
		return t;
	}
	else
	{
		return FindMin(t->left);
	}
}

FindMax例程的实现:

position FindMax(searchTree t){
	if (t==NULL)
	{
		return NULL;
	}
	while (t->right!=NULL)
	{
		t = t->right;
	}
	return t;
}

Delete例程的实现:

searchTree Delete(int x, searchTree t){
	position tmpCell;
	if (t==NULL)
	{
		cout << "Element not found!" << endl;
	}
	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);
	}
	return t;
}

删除例程中,被删除的节点有两个儿子时,用其右子树的最小的数据的数据代替该节点的数据并递归的删除那个节点。
Insert例程的实现:

searchTree Insert(int x, searchTree t){
	if (t==NULL)
	{
		t = (struct treeNode *)malloc(sizeof(struct treeNode));
		if (t==NULL)
		{
			cout << "Error!Out of place!!!" << endl;
		}
		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;
}

插入例程中,用Find例程沿树查找,若找到x则什么也不做,否则将x插入到遍历路径上的最后一点。
PrintTree例程的实现:

void PrintTree(searchTree t){
	if (t==NULL)
	{
		cout << " ";
	}
	else
	{
		PrintTree(t->left);
		cout << t->element;
		PrintTree(t->right);
	}
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值