二叉搜索树的查找,创建,删除,输出。
#include<bits/stdc++.h>
using namespace std;
#define N 7 //查找数组的长度
typedef struct treenode{
int Data;
struct treenode *left;
struct treenode *right;
}node,*Pnode;
Pnode Insert(int data,Pnode root);//向树中插入节点,不在才插
void print(Pnode root);//输出
Pnode Delete(Pnode root,int n);//删除
Pnode findmin(Pnode root);
Pnode findmax(Pnode root);
bool Search(Pnode root,int n);//查找节点
int main()
{
int data[N]={45,24,53,45,12,24,90};
Pnode root=NULL;
for(int i=0;i<N;i++)
root=Insert(data[i],root);
print(root);
cout<<endl;
root=Insert(55,root);
print(root);
cout<<endl;
root=Delete(root,24);
print(root);
cout<<endl;
int n=Search(root,45);
cout<<n<<endl;
int p=Search(root,1);
cout<<p<<endl;
return 0;
}
Pnode Insert(int data,Pnode root)
{
if(!root)
{
root=(Pnode)malloc(sizeof(node));
root->Data=data;
root->left=NULL;
root->right=NULL;
cout<<data<<"插入树中了"<<endl;
return root;
}
if(data<root->Data)
root->left=Insert(data,root->left);
else if(data>root->Data)
root->right=Insert(data,root->right);
else
cout<<data<<"已经在树中"<<endl;
return root;
}
void print(Pnode root)
{
if(root)
{
cout<<"dsf ";
print(root->left);
cout<<root->Data<<" ";
print(root->right);
}
}
Pnode Delete(Pnode root,int n)
{
if(root==NULL)
return root;
if(n<root->Data)
root->left=Delete(root->left,n);
else if(n>root->Data)
root->right=Delete(root->right,n);
else if(n==root->Data)
{
if(root->left&&root->right)
{
Pnode p=findmin(root->right);
root->Data=p->Data;
//从右子树删除最小的节点
root->right=Delete(root->right,root->Data);
}
else//只有一个二子或没有
{
Pnode p=root;
if(root->right)
root=root->right;
else
root=root->left;
delete p;
}
}
return root;
}
Pnode findmin(Pnode root)
{
if(!root)
return NULL;
else if(root->left==NULL)
return root;
return findmin(root->left);
}
Pnode findmax(Pnode root)
{
if(!root)
while(root->right!=NULL)
root=root->right;
return root;
}
bool Search(Pnode root,int n)
{
Pnode p=root;
if(!p)
return false;
if(n<p->Data)
return Search(p->left,n);
else if(n>p->Data)
return Search(p->right,n);
else
return true;
}