最近在看《数据结构与算法》,学到二叉查找树,它有一个性质就是对于节点X,左子树中所有的值都小于X的值,有子树中所有的值都大于X的值,有了这个性质,寻找一个树就非常方便,所需时间只要O(logN),比一般的朴素搜索O(N)快很多,下面就给出二叉查找树的实现
#include <iostream>
using namespace std;
struct Node
{
int value;
Node* left,*right;
Node():value(0)
{
left=right=NULL;
}
};
//找到最小的节点,返回指针
Node* FindMin(Node* n)
{
if(n->left!=NULL)
return FindMin(n->left);
else
return n;
}
//找到最大的节点,返回指针
Node* FindMax(Node* n)
{
if(n->right!=NULL)
return FindMax(n->right);
else
return n;
}
//删除节点
void Delete(Node*& n,int x)
{
if(n==NULL)//找不到节点,返回
return;
if(x>n->value)
Delete(n->right,x);
else if(x<n->value)
Delete(n->left,x);
else//找到节点
{
if(n->left!=NULL&&n->right!=NULL)//假如该节点有左右儿子的话,将右子树的最小节点代替该节点
{
Node* tmp=FindMin(n->right);
n->value=tmp->value;
Delete(tmp,tmp->value);
}
else if(n->left!=NULL)//假如只有左子树,直接将子树提上一层
{
Node* tmp=n->left;
n->value=tmp->value;
n->left=tmp->left;
n->right=tmp->right;
delete tmp;
}
else if(n->right!=NULL)//同上
{
Node* tmp=n->right;
n->value=tmp->value;
n->left=tmp->left;
n->right=tmp->right;
delete tmp;
}
else
{
delete n;
}
}
}
//插入数字,假如已经存在就不插入
void Insert(Node*& n,int x)
{
if(n==NULL)//找到位置,插入
{
n=new Node;
n->value=x;
}
if(n->value==x)//找到相同数字,不插入
return;
if(x>n->value)
{
Insert(n->right,x);
}
else
{
Insert(n->left,x);
}
}
//找到值为x的节点,返回指针
Node* Find(int x,Node*& n)
{
Node* tmp=NULL;
if(n->value==x)
return n;
else if(x>n->value&&n->right!=NULL)
{
tmp=Find(x,n->right);
}
else if(x<n->value&&n->left!=NULL)
{
tmp=Find(x,n->left);
}
return tmp;
}
//打印树
void printTree(Node* n)
{
cout<<n->value<<" ";
if(n->left!=NULL)
printTree(n->left);
if(n->right!=NULL)
printTree(n->right);
}
//删除树
void DeleteTree(Node* n)
{
if(n->left!=NULL)
DeleteTree(n->left);
if(n->right!=NULL)
DeleteTree(n->right);
delete n;
}
int main()
{
Node* n=NULL;
for(int i=5;i<10;i++)
Insert(n,i);
for(int i=1;i<5;i++)
Insert(n,i);
Delete(n,3);
printTree(n);
DeleteTree(n);
return 0;
}