#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;
}
二叉查找树
最新推荐文章于 2024-07-16 16:37:19 发布