您的位置:首页 > 理论基础 > 数据结构算法

数据结构 二叉排序树

2016-05-29 17:21 357 查看
随机产生一组关键字,利用二叉排序树的插入算法建立二叉排序树,然后删除某一指定关键字元素。

代码实现:

#include <iostream>
#include <cstdio>
#include <ctime>
#include <windows.h>

using namespace std;

typedef int ElemType;
typedef struct BSTNode
{
ElemType data;
struct BSTNode *lchild,*rchild;
} BSTNode,*BiTree;

bool Find(BiTree BST,ElemType &item) ///查找函数
{
if(BST==NULL)
{
return 0;
}
else
{
if(BST->data==item)
{
item=BST->data;
return 1;
}
else if(item<BST->data)
return Find(BST->lchild,item);
else
return Find(BST->rchild,item);
}
}

void Insert(BiTree &BST,const ElemType &item) ///插入
{
if(BST==NULL)
{
BSTNode *p=new BSTNode;
p->data=item;
p->lchild=p->rchild=NULL;
BST=p;
}
else if(item<BST->data)
Insert(BST->lchild,item);
else Insert(BST->rchild,item);
}

void CreateBSTree(BiTree &BST,ElemType a[],int n)
{
BST=NULL;
for(int i=0; i<n; i++)
{
Insert(BST,a[i]);
}
}

int Delete(BiTree &BST,const ElemType item)
{
BSTNode *t,*s;
t=BST;
s=NULL;
while(t!=NULL)///查找数据域存放item的节点,用t指向,即t为要删除的节点地址,t的双亲存放在s中
{
if(t->data==item)
break;
else if(item<t->data)
{
s=t;
t=t->lchild;
}
else
{
s=t;
t=t->rchild;
}
}
if(t==NULL)///t为一棵空树的时候
return 0;
if(t->lchild==NULL && t->rchild==NULL)///叶子节点,直接删掉即可
{
if(t==BST)
BST=NULL;
else if(t==s->lchild)
{
s->lchild=NULL;
}
else
s->rchild=NULL;
delete t;
}

else if(t->lchild==NULL || t->rchild==NULL)///只有一棵子树的时候
{
if(t==BST)
{
if(t->lchild==NULL)
{
BST=t->rchild;
}
else
BST=t->rchild;
}
else if(t==s->lchild && t->lchild!=NULL)
{
s->lchild=t->lchild;
}
else if(t==s->lchild && t->rchild!=NULL)
{
s->lchild=t->rchild;
}
else if(t==s->rchild && t->lchild!=NULL)
{
s->rchild=t->lchild;
}
else if(t==s->rchild && t->rchild!=NULL)
{
s->rchild=t->rchild;
}
delete t;
}

else if(t->lchild!=NULL && t->rchild!=NULL)///左右子树都不为空的时候
{
BSTNode *p,*q;
p=t;
q=t->lchild;
while(q->rchild!=NULL)///找t的直接前驱,记录在q中,p用来记录q的双亲;第一个左孩子的最右边的右孩子即为其直接前驱
{
p=q;
q=q->rchild;
}
t->data=q->data;///交换q和t的数据值,保留q的即可
if(p==t)///若t的前驱的双亲还是t的话,就直接删掉q结点即可
{
t->lchild=q->lchild;
}
else ///用p来记录要删结点t的前驱q的双亲,可以起到直接删掉p的作用
p->rchild=q->lchild;
delete q;
}
return 1;
}

void Inorder(BiTree BST)///中序遍历二叉排序树
{
if(BST!=NULL)
{
Inorder(BST->lchild);
cout<<BST->data<<" ";
Inorder(BST->rchild);
}
}

int main()
{
BiTree bst=NULL;
///ElemType a[10]={30,50,20,70,25,54,80,23,92,40};
ElemType a[10];
srand((int)time(0));
for(int i=0;i<10;i++)
{
a[i]=rand()%100;
}
ElemType x=70;
CreateBSTree(bst,a,10);
cout<<"The List of Inorder is:"<<endl;
Inorder(bst);
cout<<endl;
if(Find(bst,x))
{
cout<<"We Have Found the x! The x is: "<<x<<endl;
}
else cout<<"What a Pity! Can not Find the x!"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: