#include <iostream>
#include <algorithm>
#include <vector>
//二分排序树,二分查找树
struct NODE
{
int val;
NODE *lchild, *rchild;
};
int SearchNode(NODE *T, int key, NODE *f, NODE **p)
{
if(!T)
{
*p = f;
return 0;
}
else if(T->val == key)
{
*p = T;
return 1;
}
else if(T->val < key)
{
return SearchNode(T->rchild, key, T, p);
}
else
{
return SearchNode(T->lchild, key, T, p);
}
}
void InsertNode(NODE **T, int key)
{
NODE *p = NULL;
if(!SearchNode(*T, key, NULL, &p))
{
NODE *s = new NODE;
s->val = key;
s->lchild = s->rchild = NULL;
if(!p)
{
*T = s;//插入s为新的根节点
}
else if(p->val < key)
{
p->rchild = s;
}
else if(p->val > key)
{
p->lchild = s;
}
}
}
void DeleteNODE(NODE **T)
{
NODE *q = NULL;
if(!(*T)->rchild)
{
//右子树为空
q = *T;
*T = (*T)->lchild;
delete q;
}
else if(!(*T)->lchild)
{
//左子树为空
q = *T;
*T = (*T)->rchild;
delete q;
}
else
{
//左右子树均不为空,则找到前驱,与当前节点进行替换
q = *T;
NODE *s = (*T)->lchild;
while(s->rchild)
{
q = s;
s = s->rchild;
}
(*T)->val = s->val;
if(q != *T)
{
q->rchild = s->lchild;
}
else
{
q->lchild = s->lchild;
}
delete s;
}
}
int DeleteBST(NODE **T, int key)
{
if(!T)
{
return 0;
}
else if((*T)->val == key)
{
DeleteNODE(T);
}
else if((*T)->val < key)
{
return DeleteBST(&(*T)->rchild, key);
}
else
{
return DeleteBST(&(*T)->lchild, key);
}
}
int main(int nArgs, char* pArg[])
{
int a[10] = {62, 88, 58, 47, 35, 73, 51, 99, 37, 93};
NODE *T = NULL;
for(int i = 0; i < 10; ++i)
{
InsertNode(&T, a[i]);
}
std::cout << DeleteBST(&T, 47) << std::endl;
system(“pause”);
return 0;
}