《算法导论》12、二叉查找树(C++实现)

没啥好说的,都是书上的功能。

#include <iostream>
#include "stdio.h"
using namespace std;
struct Node
{
	Node *p;
	int value;
	Node *left;
	Node *right;
};
Node* root;
void inorderTreeWalk(Node* n)
{
	if (n != NULL)
	{
		inorderTreeWalk(n->left);
		cout << n->value << "  ";
		inorderTreeWalk(n->right);
	}
}
Node* treeSearch(Node* n, int value)
{
	if (n == NULL || n->value == value)
		return n;
	else
	{
		if (n->value > value)
			return treeSearch(n->left, value);
		else
			return treeSearch(n->right, value);
	}
}
Node* treeMin(Node* n)
{
	Node* r=n;
	while (r->left!=NULL)
	{
		r = r->left;
	}
	return r;
}
Node* treeMax(Node* n)
{
	Node* r = n;
	while (r->right != NULL)
	{
		r = r->right;
	}
	return r;
}
Node* treeSuccessor(Node* n)
{
	Node* x = n;
	if (n->right != NULL)
		return treeMin(n->right);
	Node* y = n->p;
	while (y != NULL && x == y->right)
	{
		x = y;
		y = y->p;
	}
	return y;
}
Node* treePredecessor(Node* n)
{
	Node* x = n;
	if (n->left != NULL)
		return treeMax(n->left);
	Node* y = n->p;
	while (y != NULL && x == y->left)
	{
		x = y;
		y = y->p;
	}
	return y;
}
Node* treeInsert(Node* n, int key)
{
	Node* y = NULL;
	Node* x = n;
	if (x == NULL)
	{
		x = new Node;
		x->p = NULL;
		x->value = key;
		x->left = NULL;
		x->right = NULL;
		root = x;
		return x;
	}
	while (x != NULL)
	{
		y = x;
		if (x->value > key)
			x = x->left;
		else
			x = x->right;
	}
	x = new Node;
	x->p = y;
	x->value = key;
	x->left = NULL;
	x->right = NULL;
	if (y != NULL)
	{
		if (key < y->value)
			y->left = x;
		else
			y->right = x;
	}
	return x;
}
void treeDelete(Node* n, Node* z)
{
	Node* x, * y;
	if (z->left == NULL || z->right == NULL)
		y = z;
	else
		y = treeSuccessor(z);
	if (y->left != NULL)
		x = y->left;
	else
		x = y->right;
	if (x != NULL)
		x->p = y->p;
	if (y->p == NULL)
		root=x;
	else if (y == y->p->left)
		y->p->left = x;
	else
		y->p->right = x;
	if (y != z)
		z->value = y->value;
	delete y;
}
void treeDestroy(Node* n)
{
	if (n != NULL)
	{
		treeDestroy(n->left);
		treeDestroy(n->right);
		delete n;
	}
}
void main()
{
	int n = 10;  //排序元素长度      
	for (int i = 0; i <n; i++)
	{
		treeInsert(root, rand() % 1000);
	}
	inorderTreeWalk(root);  //中序遍历
	cout << endl;
	Node* p = treeSearch(root, 962);
	if (p != NULL)
	{
		cout << "结果:" << p->value << endl;
		treeDelete(root, p);  //删除节点
	}
	else
		cout << "无该节点" << endl;		
	inorderTreeWalk(root);  //中序遍历
	cout << endl;
	treeDestroy(root);
	system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值