二叉查找树





依据wikipedia:给出其实现的一种:#include<iostream>
using namespace std;
struct BSTree
{
int data;
struct BSTree *leftchildren;
struct BSTree *rightchildren;};
void insert_BST(BSTree *&root,int key)
{
//没有根节点,我们创建一个根节点
if(root==NULL)
{
BSTree *tmp = new BSTree;//创建一个新的节点
tmp–>leftchildren =NULL;
tmp–>rightchildren =NULL;
tmp–>data = key;
root = tmp;// 根节点改变了,所以要传入引用!
}
else
{
if(root–>data>key)
{if(root–>leftchildren!=NULL)
insert_BST(root–>leftchildren,key);
else
{
BSTree *tmp1 =new BSTree;
tmp1–>data = key;
tmp1–>leftchildren=NULL;
tmp1–>rightchildren = NULL;root–>leftchildren=tmp1;
}
}
else
{
if(root–>rightchildren!=NULL)
insert_BST(root–>rightchildren,key);
else
{
BSTree *tmp2=new BSTree;
root–>rightchildren = tmp2;
tmp2–>data =key;
tmp2–>leftchildren =NULL;
tmp2–>rightchildren =NULL;root–>rightchildren =tmp2;
}
}}
}
//根据二叉树的特点,我们可以递归的找到要找到的关键值!
bool search_BST(BSTree *root,int key)
{
BSTree *tmp = root;
if(tmp==NULL)
return false;
else if(tmp–>data == key)
return true;
else
{
if(tmp–>data < key)
{
search_BST(tmp–>rightchildren,key);
}
else
{
search_BST(tmp–>leftchildren,key);
}
}
return true;}
//按照中序遍历打印这颗二叉树!
void inorder_BST(BSTree *root)
{
if(root!=NULL)
{
inorder_BST(root–>leftchildren);
cout<<root–>data<<” “;inorder_BST(root–>rightchildren);
}
cout<<“n”;}
void deletion_BST(BSTree *&root,int key)
{
if(root==NULL)
cout<<“error!”<<endl;
else if(root–>data < key)
{
deletion_BST(root–>rightchildren,key);}
else if(root–>data > key)
{
deletion_BST(root–>leftchildren,key);
}
else
{
if(root–>leftchildren==NULL)
{
BSTree *tmp = root–>rightchildren;
delete root;
root = tmp;
}
else if(root–>rightchildren == NULL)
{
BSTree *tmp1 = root–>leftchildren;
delete root;
root = tmp1;
}
else
{
BSTree *parent = NULL;
BSTree *tmp3 = root–>rightchildren;
while(tmp3–>leftchildren!=NULL)
{
parent = tmp3;
tmp3 = tmp3–>rightchildren;
}
root–>data = tmp3–>data;
if(parent!=NULL)
deletion_BST(parent–>rightchildren,parent–>rightchildren–>data);
else
deletion_BST(root–>rightchildren,root–>rightchildren–>data);}
}
}
int main()
{
int n;
cout<<“this pragram is produced by BruceChen(http://www.brucechen1.tk)”<<endl;
BSTree *root =NULL;
cout<<“please input the key you want to build:(-1 ends)n”;
while(1)
{
cin>>n;
if(n==–1)
break;
insert_BST(root,n);}
inorder_BST(root);
cout<<“please input the key you want to delete:n”;
int key;
cin>>key;
deletion_BST(root,key);
cout<<“after deletion:n”;
cout<<“按照中序遍历输出:n”;
inorder_BST(root);return 0;
}
参考资料:1.<<算法导论>>2.<<算法引论>>