二叉查找树

#include<iostream>
using namespace std;
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
typedef int ElementType;
SearchTree MakeEmpty(SearchTree T);
Position Find(ElementType X,SearchTree T);
Position FindMin(SearchTree T);
Position FindMax(SearchTree T);
SearchTree Insert(ElementType X,SearchTree T);
SearchTree Delete(ElementType X,SearchTree T);
ElementType Retrieve(Position P);
struct TreeNode{
	ElementType Element;
	SearchTree Left;
	SearchTree Right;
};
SearchTree MakeEmpty(SearchTree T){
	if(T!=NULL){
		MakeEmpty(T->Left);
		MakeEmpty(T->Right);
		free(T);
	}
	return NULL;
}
Position Find(ElementType X,SearchTree 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(SearchTree T){
	if(T==NULL)
		return NULL;
	else if(T->Left==NULL)
		return T;
	else
		return FindMin(T->Left);
}
Position FindMax(SearchTree T){
	if(T!=NULL)
		while(T->Right!=NULL)
			T = T->Right;
	return T;
}
SearchTree Insert(ElementType X,SearchTree T){
	if(T==NULL){
		T = (TreeNode*)malloc(sizeof(TreeNode));
		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;
}
SearchTree Delete(ElementType X,SearchTree T){
	Position TmpCell;
	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;
}
int main(){
	SearchTree T = (TreeNode*)malloc(sizeof(TreeNode));
	T = NULL;
	T = MakeEmpty(T);
	int n;	cin >> n;
	for(int i=0; i<n; ++i){
		int t;	cin >> t; 
		T = Insert(t,T);
	}
	//cout << "1" << endl; 
	cout << FindMin(T)->Element << endl;
	cout << FindMax(T)->Element << endl;
cout << "---" << endl;
SearchTree t = Find(5,T);cout << "---" << endl;
	//cout << t->Element << endl;	
	T = Delete(5,T);
	if(Find(5,T)==NULL)
		cout << "11111111111111111111" << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值