公众号:CppCoding
二叉树的性质:
若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树。
没有键值相等的节点。
二叉搜索树的时间复杂度为O(logN)
查找二叉树中的某个元素
- 若b是空树,则搜索失败,否则:
- 若x等于b的根节点的数据域之值,则查找成功;否则:
- 若x小于b的根节点的数据域之值,则搜索左子树;否则:
- 查找右子树。
插入某个元素
- 若b是空树,则将s所指结点作为根节点插入,否则:
- 若s->data等于b的根节点的数据域之值,则返回,否则:
- 若s->data小于b的根节点的数据域之值,则把s所指节点插入到左子树中,否则:
- 把s所指节点插入到右子树中。(新插入节点总是叶子节点)
删除某个元素
- 如果结点z没有孩子节点,那么只需简单地将其删除,并修改父节点,用NULL来替换z;
- 如果结点z只有一个孩子,那么将这个孩子节点提升到z的位置,并修改z的父节点,用z的孩子替换z;
- 如果结点z有2个孩子,那么查找z的后继y,此外后继一定在z的右子树中,然后让y替换z。
结点类
class BinaryNode{
public:
int element;
BinaryNode* leftchild;
BinaryNode* rightchild;
BinaryNode(int theElement,BinaryNode* lt,BinaryNode * rt):element(theElement),leftchild(lt),rightchild(rt){};
friend class BinarySearchTree;
//其他函数成员略
};
二叉搜索树类
class BinarySearchTree{
public:
BinaryNode* root;
BinarySearchTree(BinaryNode* rt) {root=rt;}
BinaryNode* findMax(BinaryNode* t) const;
BinaryNode* findMin(BinaryNode* t) const;
BinaryNode* find(int x,BinaryNode* t) const;
void insert(int x,BinaryNode* &t);
void remove(int x,BinaryNode * & t);
void removeMin(BInary* & t);
//其他函数省略
};
具体实现
//查找某一个数的结点
BinaryNode* BinarySearchtree::find(int x,BinaryNode* t)const{
while(t)
if(x<t->element)
t=t->leftchild;
else if(x>t->element)
t=t->rightchild;
else
return t;
return NULL;
}
//查找二叉搜索树的最大值
BinaryNode* BinarySearchTree::findMax(BinaryNode* t)const{
if(t)
while(t->rightchild!=NULL)
t=t->rightchild;
return t;
}
//查找最小的值
Binary* BinarySearchTree::findMin(BinaryNode* t) const{
if(t)
while(t->leftchild)
t=t->leftchild;
return t;
}
//插入一个元素
void BinarySearchTree::insert(int x,BinaryNode *& t){
if(t==NULL)
t=new BinaryNode(x,NULL,NULL);
else if(x<t->element)
insert(x,t->leftchild);
else if(x>t->element)
insert(x,t->rightchild);
else{
cout << "ERROR!!! "<< endl;
return;
}
}
//删除某一个结点
void BinarySearchTree::remove(int x,BinaryNode* & t){
if(t==NULL){
cout << "this node does not exist" << endl;
return;
}
if(x<t->element)
remove(x,t->leftchild);
else if(x>t->element)
remove(x,t->rightchild);
//当函数判断要删除的结点有两个结点,它使用其右子树中关键码最小的结点来替换该结点,在调用removeMin函数将右子树中的原最小结点删除
else if(t->leftchild!=NULL&&t->rightchild!=NULL){
t->element=findMin(t->rightchild)->element;
removeMin(t->rightchild);
}else{
BinaryNode* tmp=t;
t=(t->leftchild!=NULL)?t->leftchild:t->rightchild;
delete tmp;
}
}
void BinarySearchTree::removeMin(BinaryNode* & t){
if(t==NULL){
cout << "empty tree" << endl;
return;
}
else if(t->leftchild!=NULL){
removeMin(t->leftchild);
}else if(t->leftchild==NULL){
BinaryNode* tmp=t;
t=t->rightchild;
delete tmp;
}
}