#include <stdio.h>
#include "bi_sort_tree.h"
#define KeyType ElemType
typedef void (*Visit)(ElemType e);
int g_arr[20] = {45, 24, 12, 53, 45, 12, 24, 90, 70};
/* f是T的父节点,如果能找到节点,p是该节点的指针,否则p指向最后搜索节点的指针 */
Status SearchBST(BiTree T, KeyType key, BiTree f, BiTree *p)
{
if (!T)
{
*p = f; // f 不一定是Null.
return FAIL;
}
if (key == T->data)
{
*p = T;
return SUCCESS;
}
else if (key > T->data)
{
return SearchBST(T->rchild, key, T, p);
}
else
{
return SearchBST(T->lchild, key, T, p);
}
}
Status InsertBST(BiTree *T, KeyType key)
{
BiTree p;
BiTree s;
if (SearchBST(*T, key, NULL, &p))
{
s = (BiTree)malloc(sizeof(BiTNode));
if (NULL == s)
{
printf("%s: malloc error!\n", __FUNCTION__);
return ERROR;
}
s->lchild = NULL;
s->rchild = NULL;
s->data = key;
if (!p)
{
*T = s;
}
else if (key > p->data)
{
p->rchild = s;
}
else
{
p->lchild = s;
}
return SUCCESS;
}
else
{
printf("BST has the same key(%d)!\n", key);
return FAIL;
}
}
Status delete(BiTree *p)
{
BiTree q;
BiTree s;
if (!((*p)->lchild))
{
q = *p;
*p = (*p)->rchild;
free(q);
}
else if (!((*p)->rchild))
{
q = *p;
*p = (*p)->lchild;
free(q);
}
else
{
#if 0 // method 1
q = *p;
s = (*p)->lchild;
while (s->rchild)
{
s = s->rchild;
}
s->rchild = (*p)->rchild;
*p = (*p)->lchild;
free(q);
#else //method 2
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;
}
free(q);
#endif
}
}
Status DeleteBST(BiTree *T, KeyType key)
{
if (!(*T))
{
printf("don't find the node(key=%d), so can't delete it!\n", key);
return FAIL;
}
else
{
if ((*T)->data == key)
{
return delete(T);
}
else if ((*T)->data > key)
{
return DeleteBST(&(*T)->lchild, key);
}
else
{
return DeleteBST(&(*T)->rchild, key);
}
}
}
void visit(ElemType e)
{
printf("e = %d, " ,e);
return;
}
void traverse(BiTree T, Visit v)
{
if (T)
{
traverse(T->lchild, v);
(*v)(T->data);
traverse(T->rchild, v);
}
return;
}
void CreatBST(BiTree *T, int n)
{
int i;
for (i = 0; i < n; i++)
{
InsertBST(T, g_arr[i]);
}
return;
}
int main(void)
{
BiTree T = NULL;
KeyType key = 24;
CreatBST(&T, 8);
traverse(T, visit);
DeleteBST(&T, key);
printf("after delete key=%d!\n", key);
traverse(T, visit);
return 0;
}