#include <stdlib.h>
#include <stdio.h>
typedef struct node
{
int key;
struct node *left;
struct node *right;
} Btree;
Btree *InsertBtree(Btree *t,int x)
{
Btree *f = NULL,*p;
p = t;
while (p)
{
if (x == p->key)
return t;
f = p;
if (x < p->key)
p = p->left;
else
p = p->right;
}
p = (Btree *)malloc(sizeof(Btree));
p->key = x;
p->left = p->right = NULL;
if (t == NULL)
t = p;
else
{
if (x < f->key)
f->left = p;
else
f->right = p;
}
return t;
}
void DeleteBstree(Btree *t,int x)
{
Btree *p = t;
Btree *f = NULL;
while (p != NULL)
{
if (x == p->key)
break;
else
{
f = p;
p = (x < p->key) ? p->left : p->right;
}
}
printf("\n%d ",p->key);
printf("%d ",f->key);
while (p != NULL)
{
if (p->left != NULL)
{
f = p->left;
if (f->right != NULL)
{
p->key = f->right->key;
p = f->right;
}
else
{
p->key = p->left->key;
f = p;
p = p->left;
}
continue;
}
else if (p->right != NULL)
{
if (f->left == p)
f->left = p->right;
else
f->right = p->right;
p->key = -1;
p = NULL;
}
else
{
p->key = -1;
p = NULL;
}
}
return t;
}
Btree *CreateTree()
{
Btree * t = NULL;
int key;
printf("\nPlease input a number until -1 endBye :\n");
scanf("%d",&key);
while (key != -1)
{
t = InsertBtree(t,key);
scanf("%d",&key);
}
return t;
}
void Mid_order(Btree *t)
{
if (t == NULL)
return;
else
{
Mid_order(t->left);
if (t->key != -1)
{
printf("%d ",t->key);
}
Mid_order(t->right);
}
}
int main()
{
Btree *t;
t = CreateTree();
Mid_order(t);
DeleteBstree(t,12);
printf("\n");
Mid_order(t);
}
二叉树删除前面节点(C语言初始版)
最新推荐文章于 2024-09-13 23:06:42 发布