二叉排序树的基本操作
#include<bits/stdc++.h>
using namespace std;
struct BiTree{
int data;
struct BiTree *lchild,*rchild;
};
typedef BiTree* node;
node search(int T,node root)
{
node h=new struct BiTree;
h=root;
while(h)
{
if(T<h->data){
h=h->lchild;
}
else if(T>h->data){
h=h->rchild;
}
else if(T==h->data){
return h;
}
}
return NULL;
}
node FindMax(node root)
{
node h=new struct BiTree;
h=root;
if(h){
while(h->rchild) h=h->rchild;
}
return h;
}
node FindMin(node root)
{
node h=new struct BiTree;
h=root;
if(h){
while(h->lchild) h=h->lchild;
}
return h;
}
node insert(int T,node root)
{
if(root==NULL){
root=new struct BiTree;
root->data=T;
root->lchild=NULL;
root->rchild=NULL;
}
else{
if(T<root->data){
root->lchild=insert(T,root->lchild);
}
else if(T>root->data){
root->rchild=insert(T,root->rchild);
}
}
return root;
}
node Delete(int T,node root)
{
if(search(T,root)==NULL) cout<<"the value is not found"<<endl;
else{
if(T<root->data){
root->lchild=Delete(T,root->lchild);
}
else if(T>root->data){
root->rchild=Delete(T,root->rchild);
}
else if(T==root->data){
if(root->lchild!=NULL&&root->rchild!=NULL){
node temp=FindMin(root->rchild);
root->data=temp->data;
root->rchild=Delete(temp->data,root->rchild);
}
else{
if(root->rchild==NULL&&root->lchild!=NULL){
root=root->lchild;
}
else if(root->rchild!=NULL&&root->lchild==NULL){
root=root->rchild;
}
else{
root=NULL;
}
}
}
}
return root;
}
node create_a_tree(int n)
{
node head=new struct BiTree;
head=NULL;
for(int i=0;i<n;i++){
int a;cin>>a;
head=insert(a,head);
}
return head;
}
void printt(node head)
{
if(head){
printt(head->lchild);
cout<<head->data<<" ";
printt(head->rchild);
}
}
int main()
{
int n;cin>>n;
node root=create_a_tree(n);
printt(root);
}