二叉排序树,若有左子树,则左子树上所有结点数据小于根结点数据,
若有右子树,则右子树上所有结点数据大于根结点数据。
左,右子树本身又各是一棵二叉排序树。
#include<stdio.h>
typedef struct bst
{
int data;
struct bst *left;
struct bst *right;
}BSTree;
void InsertBST(BSTree *t,int key)
{
BSTree *p,*parent,*head;
//if(!(p=(BSTree*)malloc(sizeof(BSTree*))))
if(!(p=(BSTree*)malloc(sizeof(BSTree))))
{
printf("malloc error");
exit(0);
}
p->data = key;
p->left = p->right = NULL;
head = t;
while(head)
{
parent = head;
if(key < head->data)
head = head->left;
else
head = head->right;
}
if(key < parent->data)
parent->left = p;
else
parent->right = p;
}
void createBST(BSTree *t,int data[],int n)
{
int i;
t->data = data[0];
t->left = t->right = NULL;
for(i=1;i<n;i++)
InsertBST(t,data[i]);
}
void BST_LDR(BSTree *t)
{
if(t)
{
BST_LDR(t->left);
printf("%d ",t->data);
BST_LDR(t->right);
}
return ;
}
BSTree *SearchBST(BSTree *t,int key)
{
if(!t || t->data == key)
return t;
else if(key >t->data)
return (SearchBST(t->right,key));
else
return (SearchBST(t->left,key));
}
void BST_Delete(BSTree *t,int key)
{
BSTree *p,*parent,*l,*ll;
int child = 0;
if(!t) return;
p = t;
parent = p;
while(p)
{
if(p->data == key)
{
if(!p->left && !p->right)
{
if(p == t)
{
free(p);
}
else if(child == 0)
{
parent->left = NULL;
free(p);
}
else
{
parent->right = NULL;
free(p);
}
}
else if(!p->left)
{
if(child == 0)
parent->left = p->right;
else
//parent->left = p->left;
parent->right = p->right;
free(p);
}
else if(!p->right)
{
if(child == 0)
//parent->right = p->right;
parent->left = p->left;
else
parent->right = p->left;
free(p);
}
else
{
ll = p;
l = p->right;
while(l->left)
{
ll = l;
l=l->left;
}
p->data = l->data;
ll->data =1;
ll->left = NULL;
free(ll);
}
p = NULL;
}
else if (key < p->data)
{
child = 0;
parent = p;
p = p->left;
}
else if(key > p->data)
{
child = 1;
parent = p;
p = p->right;
}
}
}
int main()
{
int key,i;
int source[10]={54,90,6,69,12,37,92,28,65,83};
for(i=0;i<10;i++)
printf("%d ",source[i]);
printf("\n");
BSTree bst,*pos;
createBST(&bst,source,10);
printf("result:");
BST_LDR(&bst);
printf("\n");
printf("enter a num:");
scanf("%d",&key);
pos = SearchBST(&bst,key);
if(pos)
printf("search succeed address is %x\n",pos);
else
printf("search failed\n");
BST_Delete(&bst,key);
printf("after delete:\n");
BST_LDR(&bst);
printf("\n");
return 0;
}