实现二叉搜索树类,仅供参考
//二叉搜索树
//只写了类方法的具体实现,由于二叉搜索树的查找效率与树的高度有关,而树的高度与初始化数据的排列有关,《算法导论》中给出一种随机生成序列的方法,以及下一篇红黑树排列的方法,可以有效的稳定树的高度。
//so 这篇暂时不写主函数,为下篇红黑树做准备
// Author's E-mail : focus.zhaos@gmail.com
//Feel free to contact me for comments on my work !
#include<iostream>
using namespace std;
//节点类node
class node{
public:
node* left;
node* right;
node* parents;
int value;
node() = default;
};
//二叉搜索树类
class tree{
public:
node root; //根节点
void inorderTreeWalk(node *x); //递归中序遍历
void iterative_inorderTreeWalk(); //迭代中序遍历
node* treeSearch(node *x, int k); //递归查找函数,返回一个指向关键字为k的节点的指针,否则返回NIL
node* iterative_treeSearch(int k); //迭代查找函数
node* treeMinimum(node* p); //返回以p为根节点的子树的最小元素
node* treeMaxmum(node* p); //返回以p为根节点的子树的最大元素
node* treeSuccessor(node &x); //返回一颗二叉搜索树中结点的后继,若是最大结点则返回NIL
void treeInsert(node &z); //把新结点插入到二叉树中
void transPlant(node* u, node* v); //在二叉搜索树内移动子树,用以v为根的子树替换以u为根的子树
void treeDelete(node &z); //在二叉搜索树中删除结点z
};
//递归中序遍历
void tree::inorderTreeWalk(node* x){
if(x!=NULL){
inorderTreeWalk(x->left);
cout<<x->value<<endl;
inorderTreeWalk(x->right);
}
}
//迭代中序遍历,用栈实现
void tree::iterative_inorderTreeWalk(){
}
//递归查找函数
node* tree::treeSearch(node* x, int k){
if((k == x->value)||(k == NULL)){
return x;
}
else if (k < x->value){
return treeSearch(x->left, k);
}
else{
return treeSearch(x->right, k);
}
}
//迭代查找函数
node* tree::iterative_treeSearch(int k){
node* p = &root;
while((p != NULL)||(p->value != k)){
if (p->value < k) {
p = p->right;
}
else{
p = p->left;
}
}
return p;
}
//返回以p为根子树的最小元素
node* tree::treeMinimum(node* p){
while(p->left != NULL){
p = p->left;
}
return p;
}
//返回以p为根子树的最大元素
node* tree::treeMaxmum(node* p){
while(p->right != NULL){
p = p->right;
}
return p;
}
//返回一颗二叉搜索树中结点的后继,若是最大结点则返回NIL
node* tree::treeSuccessor(node &x){
if (x.right != NULL) {
return treeMinimum(x.right);
}
node* y = x.parents;
while((y != NULL)&&(&x == y->right)){
x = *y;
y = y->parents;
}
return y;
}
//把新结点插入到二叉树中
void tree::treeInsert(node &z){
node* y = NULL;
node* x = &root;
while(x != NULL){
y = x;
if(z.value < x->value){
x = x->left;
}
else if (z.value > x->value){
x = x->right;
}else{
cout<<"the value already exist !"<<endl;
return ;
}
}
z.parents = y;
if(y == NULL){
root = z; //tree is empty
}else if (z.value < y->value){
y->left = &z;
}else{
y->right = &z;
}
}
//在二叉搜索树内移动子树,用以v为根的子树替换以u为根的子树
void tree::transPlant(node* u, node* v){
if(u->parents == NULL){
root = *v;
}else if (u == u->parents->left){
u->parents->left = v;
}else{
u->parents->right = v;
}
if (v != NULL) {
v->parents = u->parents;
}
}
//在二叉搜索树中删除结点z
void tree::treeDelete(node &z){
if(z.left == NULL){
transPlant(&z, z.right);
}else if(z.right == NULL){
transPlant(&z, z.left);
}else{
node* y = treeSuccessor(z);
if(y->parents != &z){
transPlant(y, y->right);
y->right = z.right;
y->right->parents = y;
}
transPlant(&z, y);
y->left = z.left;
y->left->parents = y;
}
}
//主函数
int main(){
/*waiting for your code */
}