自己写的二叉排序树,实现结点插入,查找,删除功能;但是始终有有关问题,就大神们帮帮忙,帮小弟我调试成功
自己写的二叉排序树,实现结点插入,查找,删除功能;但是始终有问题,就大神们帮帮忙,帮我调试成功!
RT,
只能插入2个结点,插入第3个就把第2个覆盖了,不知道是什么情况。
代码如下:
RT,
只能插入2个结点,插入第3个就把第2个覆盖了,不知道是什么情况。
代码如下:
#include <stdio.h>
#include <iostream.h>
#include <stdlib.h>
using namespace std;
typedef struct BiTNode
{
int data;
struct BiTNode* lChild;
struct BiTNode* rChild;
} BSTree,BTNode;
//查找key值
bool Search(BSTree*& Btree,int key ,BSTree*& father ,BSTree*& p)
{
if(!Btree)
{
p=father;
return false;
}
else if(Btree->data==key)
{
p=Btree;
return true;
}
else if(Btree->data<key)
{
return Search(Btree->lChild,key,Btree,p);
}
else
{
return Search(Btree->rChild,key,Btree,p);
}
}
//插入结点
bool InsertBST(BSTree*& Btree,BSTree*& p,int& key)
{
BSTree* s=NULL;
if(!Search(Btree,key,Btree,p))
{
s=(BTNode*)malloc(sizeof(BTNode));
s->data=key;
s->lChild=NULL;
s->rChild=NULL;
if(!p) Btree=s;
else if(p->data > key)
{
p->lChild=s;
}
else
{
p->rChild=s;
}
return true;
}
else
return false;
}
//删除结点
bool deleteBST(BSTree*& Btree,int& key)
{
BSTree* p=NULL;
BSTree* f=Btree;
if(Search(Btree,key,f,p))
{
if(p->lChild==NULL &&p->rChild==NULL ) //叶结点
{
if(f->data>p->data) f->lChild=NULL;
else f->rChild=NULL;
free(p);
}
else if(p->rChild==NULL) //有左孩子
{
if(f->data > p->data) f->lChild=p->lChild;
else f->rChild=p->lChild;;
free(p);
}
else if(p->lChild==NULL) //有右孩子
{
if(f->data > p->data) f->lChild=p->rChild;
else f->rChild=p->rChild;;
free(p);
}
else //左右孩子都不为空
{
//找到p结点左子树中最右边的结点
BSTree* n=p->lChild;