数据结构之二叉搜索树c++ 简单版

来源:互联网 发布:手机免流量软件 编辑:程序博客网 时间:2024/05/22 16:56

//二叉搜索树,简单的来讲就是一种左孩子小于双亲节点和右孩子大于双亲节点的二叉树。

#include "stdafx.h"
#include<iostream>
#include<assert.h>
using namespace std;
template<class T>
class Btree
{
protected:
typedef struct BtNode 
{
T  data;
BtNode *leftchild;
BtNode *rightchild;
};
private:
BtNode *root;
BtNode * buynode(const T x)                  //开辟节点并且赋值。
{
BtNode *s = new BtNode;
s->data = x;
return s;
}
void insert(BtNode *&r,const T x)                //给根节点为r的二叉树 插入x 下面有详细介绍。
{
if (r == NULL)
{
r = buynode(x);
r->leftchild = r->rightchild = NULL;
}
if(r->data >x)
{
insert(r->leftchild,x);
}
if (r->data < x)
{
insert(r->rightchild,x);
}


}
void print(BtNode *s) const  // 输出函数 ,中序遍历 ,从大到小输出
{
if(s != NULL)
{
print(s->leftchild);
cout<<s->data<<"  ";
print(s->rightchild);
}
}
BtNode* find(BtNode *t,T x)       // 查找 根节点为t 里面数据为x的节点 并返回该节点。
{
if(t==NULL) return NULL;
else if (t->data > x)
{
return find(t->leftchild,x);
}
else if(t->data < x)
{
return find(t->rightchild,x);
}
else
return t;
}
void removeBT(BtNode *&s,const T x)  //删除根节点为s,其中数据为x的节点。
{
if(s!=NULL)
{
BtNode *q=s;
if(s->data > x)
{
removeBT(s->leftchild,x);
}
else if(s->data < x)
{
removeBT(s->rightchild,x);
}

else if(q->leftchild != NULL && q->rightchild != NULL)
{
q=q->rightchild;
while(q->leftchild != NULL) q=q->leftchild;
s->data = q->data;
delete q;
return;
}
else 
{
if(s->leftchild==NULL) s=s->rightchild;
else  s=s->rightchild;
delete q;
}
}
}
public:
Btree():root(NULL)
{
}
void insert(T x)
{
insert(root,x);
}
void insert(T* begin, T* end)
{
assert(begin != NULL  &&  end != NULL);
while (begin++ != end)
{
insert(*begin);
}
}
void print()
{
print(root);
}
BtNode * find(T x)
{
return find(root,x);
}
void removeBT(T x)
{
removeBT(root,x);
}
};
void main()
{
Btree<int> mytree;
mytree.insert(53);
mytree.insert(78);
mytree.insert(65);
mytree.insert(17);
mytree.insert(87);
mytree.insert(9);
mytree.insert(81);
mytree.insert(45);
mytree.insert(23);
int a[10]={12,23,34,45,56,67,78,89,90,0};
mytree.insert(&a[0],&a[9]);
mytree.print();
// cout<<mytree.find(0)<<endl;
mytree.removeBT(58);
mytree.print();

这个是插入函数讲解。//////////////////////////////////////////////////////////
}

查找函数/////////////////////////////////////////////////////

删除函数//////////////////////////////////////////////////////

删除一共三种情况

1 左右子树都不为空的节点

2 左子树为空的节点

3 右子树为空的节点

写这个目的只是为了锻炼表达能力,如果觉得不足之处,希望您指出,本人估计连菜鸟都算不上。

 

原创粉丝点击