12 二叉查找树

#include <iostream>
using namespace std;

typedef struct Node			//树结点定义
{
	int key;
	Node *lchild, *rchild, *parent; 
}Node, *BSTree;
 

Node * BSTreeSearch(BSTree T, int k)			 //遍历查找
{
	if(T == NULL || k == T->key)
		return T;
	if(k < T->key)
		return BSTreeSearch(T->lchild, k);
	else
		return BSTreeSearch(T->rchild, k);
}
 

Node * IterativeBSTreeSearch(BSTree T, int k)	 //遍历查找的非递归版本
{
	while(T != NULL && k != T->key)
	{
		if(k < T->lchild->key)
			T = T->lchild;
		else
			T = T->rchild;
	}
	return T;
}

 

Node * BSTreeMinimum(BSTree T)					//最小值
{
	while(T->lchild != NULL)
		T = T->lchild;
	return T;
}
 
Node * BSTreeMaximum(BSTree T)					//最大值
{
	while(T->rchild != NULL)
		T = T->rchild;
	return T;
}
 
Node *BSTreeSuccessor(Node *x)					//结点x的中序后续结点
{
	if(x->rchild != NULL)
		return BSTreeMinimum(x->rchild);
	Node *y = x->parent;
	while(y != NULL && x == y->rchild)
	{
		x = y;
		y = y->parent;
	}
	return y;
}
 
void BSTreeInsert(BSTree &T, int k)				//插入,注意BSTree作为引用型指针参数的作用,可以直接传值
{
	Node *y = NULL;
	Node *x = T;
	Node *z = new Node;
	z->key = k;
	z->lchild = z->parent = z->rchild = NULL;
 
	while(x != NULL)
	{
		y = x;
 
		if(k < x->key)
			x = x->lchild;
		else
			x = x->rchild;
	}
 
	z->parent = y;
	if(y == NULL)
	{
		T = z;
	}
	else
		if(k < y->key)
			y->lchild = z;
		else
			y->rchild = z;
}
 
Node* BSTreeDelete(BSTree &T, Node *z)			//删除节点z		
{
	Node *x, *y;
	// z是要删除的节点,而y是要替换z的节点
	if(z->lchild == NULL || z->rchild == NULL)   
		y = z;   // 当要删除的z至多有一个子树,则y=z;
	else
		y = BSTreeSuccessor(z);  // y是z的后继
	if(y->lchild != NULL)
		x = y->lchild;  
	else
		x = y->rchild;      //注意,x最多只有一个子树
	if(x != NULL)                   
		x->parent = y->parent;  
	if(y->parent == NULL)   
		T = x;
	else if(y == y->parent->lchild)   
		y->parent->lchild = x;
	else
		y->parent->rchild = x;
	if(y != z)   //y=z的情况是z只有1个子树的情况
		z->key = y->key;
	return y;
}
 
 
 
void InBSTree(BSTree T)
{
	if(T != NULL)
	{
		InBSTree(T->lchild);
		cout << T->key << " ";
		InBSTree(T->rchild);
	}
}
 
 
 
int main()
{
	int m;
	BSTree T = NULL;
	for(int i=0; i<6; ++i)
	{
		cin >> m;
		BSTreeInsert(T, m);
		cout << "二叉查找树中序查找:";
		InBSTree(T);
		cout << endl;
	}
	cout << "删除根节点后:";
	BSTreeDelete(T, T);
	InBSTree(T);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值