#include<iostream>
typedef struct BSTNode {
int data;
struct BSTNode* lchild;
struct BSTNode* rchild;
}*BSTree;
using namespace std;
void insert(BSTree& t,int e)
{
if (!t)
{
t = new BSTNode;
t->data = e;
t->lchild = NULL;
t->rchild = NULL;
}
else
{
if (t->data < e)
{
insert(t->rchild, e);
}
else
{
insert(t->lchild, e);
}
}
}
void InOrder(BSTree& t)
{
if (t)
{
if(t->lchild)
InOrder(t->lchild);
cout << t->data << " ";
if (t->rchild)
InOrder(t->rchild);
}
}
BSTree CreateBSTree()
{
BSTree tree = NULL;
BSTree& t = tree;
cout << "输入你想要排序的数集合:" << endl;
while (true)
{
int e;
cin >> e;
if (e == 0)
{
cout << "输入完毕,集合结果为:" << endl;
break;
}
else
{
insert(t, e);
}
}
InOrder(tree);
return tree;
}
void DeleteTree(BSTree& t)
{
cout << "输入要删除的结点:" << endl;
int v;
cin >> v;
BSTree p = t, f=NULL, s, q=NULL;
if (!t) return;
//find p,f
while (p)
{
if (p->data == v) break;
f = p;
if (p->data < v)
p = p->rchild;
else
p = p->lchild;
}
if (!p) return; //未找到要delete 的结点
if (p->lchild&&p->rchild)
{
//find s,q --前驱
q = p;
s = p->lchild;
while (s->rchild)
{
q = s;
s = s->rchild;
}
p->data = s->data;
if (q!=p)
{
q->rchild = s->lchild;
}
else
{
q->lchild = s->lchild;
}
delete s;
}
else
{
if (!p->rchild)
{
q = p;
p = p->lchild;
}
else if (!p->lchild)
{
q = p;
p = p->rchild;
}
//删除根节点
if (!f)
{
t = p;
}
else if(q==f->lchild)
{
f->lchild = p;
}
else if (q == f->rchild)
f->rchild = p;
delete q;
}
InOrder(t);
}
int main() {
BSTree t = CreateBSTree();
DeleteTree(t);
return 0;
}
25 18 69 5 20 32 45 0
18