参考:邓俊辉老师《数据结构C++语言实现》
继承BinTree类
注意:使用template时,若类函数定义和实现没有写在同一文件中,可能出现连接错误
解决方案:1、定义与实现写在同一文件;2、使用时include所有用到的.h与.cpp文件。
类定义:
//
// Created by Jayson on 2023/8/1.
//
#ifndef TREEFAMILY_BST_H
#define TREEFAMILY_BST_H
#include "BinTree.h"
template<typename T>
class BST :public BinTree<T>{
public:
BinNode<T>* _hot;//返回搜索命中节点的父亲
virtual BinNode<T>*& search(T e);//定义为virtual是为了在派生的平衡二叉搜索树中重写他们
virtual BinNode<T>* insert(T e);
virtual bool remove(T e);
};
#endif /
实现:
BST的search方法很重要,是插入删除以及AVL,红黑树的基础
//
// Created by Jayson on 2023/8/1.
//
#include "BST.h"
#include "iostream"
using namespace std;
template<typename T>
//搜索注意返回类型为引用
static BinNode<T>*& searchIN(BinNode<T> *&v,T e, BinNode<T> *&hot) {
if(!v || v->value == e)return v;
hot = v;
if(e < v->value) return searchIN(v->lchild,e,hot);
else return searchIN(v->rchild,e,hot);
}
template<typename T>
BinNode<T>*& BST<T>::search(T e) {
_hot = NULL;
BinNode<T>*& result = searchIN(this->_root,e,_hot);
return result;
}
//插入
template<typename T>
BinNode<T>* BST<T>::insert(T e) {
BinNode<T>*& x = search(e);
if(x)return x;
x = new BinNode<T>(e,_hot);
this->_size++;
this->updateHeightAbove(x);
return x;
}
//删除
template<typename T>
static BinNode<T>* removeAT(BinNode<T>*&x,BinNode<T>*&hot){
BinNode<T>* succ = NULL;
if(!x->rchild){
succ = x = x->lchild;
}else if(!x->lchild){
succ = x = x->rchild;
}else{
succ = x->succ();
swap(x->value,succ->value);
if(succ->parent == x){
x->rchild = succ->rchild;
succ->rchild->parent = x;
succ = x->rchild;
hot = x;
}else{
BinNode<T>* w = succ->parent;
w->lchild = succ->rchild;
succ->rchild->parent = w;
succ = w->lchild;
hot = w;
}
}
return succ;
}
template<typename T>
bool BST<T>::remove(T e) {
BinNode<T>*& x = search(e);
if(!x) return false;
removeAT(x,_hot);
this->_size--;
this->updateHeightAbove(_hot);
return true;
}
测试代码
#include "BST.h"
#include "BST.cpp"
#include "BinTree.h"
#include "BinTree.cpp"
#include <iostream>
using namespace std;
int main(){
BST<float>* bst = new BST<float>();
bst->insert(6);
bst->insert(2);
bst->insert(5);
bst->insert(7);
bst->insert(4);
bst->insert(3);
bst->insert(1);
(*bst).insert(3.5);
bst->travIn(bst->root());
bst->remove(3);
cout<<endl;
bst->travIn(bst->root());
}