源代码如下所示:
#include<iostream>
using namespace std;
class BSTree
{
public:
int data;
BSTree *left;
BSTree *right;
BSTree(int data,BSTree *left = NULL ,BSTree * right= NULL)
{
this->data= data;
this->left= left;
this->right= right;
}
};
void insert_BST(BSTree * &root, int n)// 这个*&好åƒå¾ˆç¥žå¥‡çš„æ ·åï¼Œç›´æŽ¥ä¼ è¿‡æ¥ï¼ŒçœåŽ»äº†å¤åˆ¶çš„麻烦
//è€Œä¸”å¿…é¡»è¿™æ ·
{
if(root==NULL)
{
BSTree * temp= new BSTree(n);
root = temp;
}
else
{
if(root->data>n)
{
if(root->left!=NULL)
insert_BST(root->left,n);
else
{
BSTree * temp1 = new BSTree(n);
root->left=temp1;
}
}
else
{
if (root->right!=NULL)
insert_BST(root->right,n);
else
{
BSTree * temp2= new BSTree(n);
root->right= temp2;
}
}
}
}
bool search_BST(BSTree *root, int key)//为了ä¿è¯rootçš„ä¸è¢«ç¯¡æ”¹ï¼Œè¿˜æ˜¯ä½¿ç”¨
{//指针,ä¸ä¼ 指针的地å€äº†å§
BSTree *temp=root;
if(temp==NULL)
return false;
else if(temp->data==key)
return true;
else
{
if(temp->data<key)
search_BST(temp->right,key);
else
search_BST(temp->left,key);
}
//ä¸æƒ³åœ¨è¿™é‡ŒåŠ 上return true;
}
/*
void print(int a)
{
cout<<a<<endl;
}*/
void inorder_BST(BSTree *root)
{
if(root->left!=NULL)
inorder_BST(root->left);
cout<<root->data<<endl;//在函数的调用这里还是有点问题,è¦çœ‹è€å¸ˆçš„课件,好åƒæ˜¯è¿™ä¹ˆå›žäº‹
if(root->right!=NULL)
inorder_BST(root->right);
/*
ä¸å¦‚下é¢çš„代ç 简å•
if(root!=NULL)
{
inorder_BST(root->leftchildren);
cout<<root->data<<" ";
inorder_BST(root->rightchildren);
}
cout<<"\n";
*/
}
int findmax(BSTree *root)
{
int max=0;
if(root->right!=NULL)
max=findmax(root->right);
else
max=root->data;
return max;
}
void deletion_BST(BSTree *& root,int key)
{
if(root==NULL)
cout<<"error"<<endl;
else if(root->data<key)
{
deletion_BST(root->right,key);
}
else if(root->data>key)
{
deletion_BST(root->left,key);
}
else
{
if(root->left==NULL)
{
BSTree *tmp=root->right;
delete root;
root=tmp;
}
else if(root->right==NULL)
{
BSTree *tmp=root->right;
delete root;
root=tmp;
}
else
{
//BSTree *par=NULL;
BSTree *tmp3 = root->right;
int s=findmax(tmp3->left);
root->data=tmp3->data;
deletion_BST(root->right,tmp3->data);
}
}
}
int main()
{
int n;
cout<<"this cpp is produced by chengyang"<<endl;
BSTree * root = NULL;
cout<<"please input the key you want to build a BST tree, unless you put -1"<<endl;
while(1)
{
cin>>n;
if(n==-1)
{
break;
}
else
{
insert_BST(root,n);
}
}
inorder_BST(root);
cout<<"this is the inorder of the binary tree"<<endl;
insert_BST(root,234);
cout<<"after insert 234 in to the tree"<<endl;
inorder_BST(root);
cout<<"this is the inorder of the binary tree"<<endl;
deletion_BST(root,234);
cout<<"after deletion of 234"<<endl;
inorder_BST(root);
system("pause");
return 0;
}