二叉排序树,结点删除的问题,折腾很久了,求解脱
vs2010
#include<iostream>
using namespace std;
static int i = 1;
struct Node //结点定义
{
int ch;
Node* lchild;
Node* rchild;
};
void insertBST(Node *&t,int key)
{
if(t == NULL)
{
t = new Node;
t->ch = key;
t->lchild = NULL;
t->rchild = NULL;
}
else
if(key < t->ch)
insertBST(t->lchild,key);
else
insertBST(t->rchild,key);
}
Node* searchBST(Node* tree,int key)
{
if(NULL == tree||key == tree->ch)
return tree;
if(key < tree->ch)
searchBST(tree->lchild,key);
else
searchBST(tree->rchild,key);
}
void deleteNode(Node *&p) //删除结点
{
Node* temp = new Node;
if(NULL == p->rchild) //根据主程序的测试用例,这块好像就有问题,但一直没弄明白
{
temp = p;
p = p->lchild;
delete temp;
cout<<"删除了!\n";
}
else
if(NULL == p->lchild)
{
temp = p;
p = p->rchild;
delete temp;
}
else
{
Node* track = new Node;
track = p;
temp = p->lchild;
while(NULL != temp->rchild)
{
track = temp;
temp = temp->rchild;
}
p->ch = temp->ch;
if(track == p)
track->lchild = temp->lchild;
else
track->rchild = temp->lchild;
delete temp;
}
}
void show(const Node* Tree) //先序遍历
{
if(Tree != NULL)
{
cout<<i++<<'\t'; //作为调试信息
show(Tree->lchild);
cout<<Tree->ch<<'\t';
show(Tree->rchild);
}
}
int main()
{
int buf[7] ={8,4,2,6,7,1,3};
Node *tree = NULL;
for(int i = 0;i < 7;i ++)
insertBST(tree,buf[i]);
//show(tree);
//cout<<endl;
Node *tmp = searchBST(tree,1);
cout<<tmp->ch<<endl;
deleteNode(tmp);
show(tree); //这里报错说,访问冲突,应该是上面结点删除的问题吧
return 0;
}
求大神,求解脱,搞了老久了!