1.删除时采用后序遍历即先删除左右结点再删除根结点
void dele_x(Node *p){
if(p){
printf("%d ",p->data);
dele_x(p->lchild);
dele_x(p->rchild);
free(p);
}
}
2.要删除结点通过层次遍历进行查找,依次判断p,p->lchild,p->rchild是否等于值x,若等于则删除,跳到删除函数,若不等于则入队列
void search(Node *p,int x){
Queue Q;
initQueue(&Q);
if(p!=NULL){
if(p->data==x){
dele_x(p);
return;
}
EnQueue(&Q,p);
while(!emptyQueue(Q)){
p=DeQueue(&Q);
if(p->lchild!=NULL){
if(p->lchild->data==x)
dele_x(p->lchild);
else
EnQueue(&Q,p->lchild);
}
if(p->rchild!=NULL){
if(p->rchild->data==x)
dele_x(p->rchild);
else
EnQueue(&Q,p->rchild);
}
}
}
}
3.所有代码
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 10
typedef struct Node{
int data;
struct Node *lchild,*rchild;
}Node;
typedef struct{
Node *data[MaxSize];
int front,rear;
}Queue;
void initQueue(Queue *Q){
Q->front=Q->rear=0;
}
bool emptyQueue(Queue Q){
if(Q.front==Q.rear){
return true;
}
else{
return false;
}
}
bool EnQueue(Queue *Q,Node *p){
if((Q->rear+1)%MaxSize==Q->front){
return false;
}
Q->data[Q->rear]=p;
Q->rear=(Q->rear+1)%MaxSize;
return true;
}
int DeQueue(Queue *Q){
if(Q->rear==Q->front){
return false;
}
Q->front=(Q->front+1)%MaxSize;
return Q->data[Q->front-1];
}
void dele_x(Node *p){
if(p){
printf("%d ",p->data);
dele_x(p->lchild);
dele_x(p->rchild);
free(p);
}
}
void search(Node *p,int x){
Queue Q;
initQueue(&Q);
if(p!=NULL){
if(p->data==x){
dele_x(p);
return;
}
EnQueue(&Q,p);
while(!emptyQueue(Q)){
p=DeQueue(&Q);
if(p->lchild!=NULL){
if(p->lchild->data==x)
dele_x(p->lchild);
else
EnQueue(&Q,p->lchild);
}
if(p->rchild!=NULL){
if(p->rchild->data==x)
dele_x(p->rchild);
else
EnQueue(&Q,p->rchild);
}
}
}
}
int main() {
Node *p=(Node *)malloc(sizeof(Node));
p->data=1;
p->lchild=NULL;
p->rchild=NULL;
Node *m=(Node *)malloc(sizeof(Node));
m->data=2;
m->lchild=NULL;
m->rchild=NULL;
p->lchild=m;
Node *n=(Node *)malloc(sizeof(Node));
n->data=3;
n->lchild=NULL;
n->rchild=NULL;
p->rchild=n;
Node *a=(Node *)malloc(sizeof(Node));
a->data=4;
a->lchild=NULL;
a->rchild=NULL;
m->lchild=a;
Node *b=(Node *)malloc(sizeof(Node));
b->data=5;
b->lchild=NULL;
b->rchild=NULL;
m->rchild=b;
Node *c=(Node *)malloc(sizeof(Node));
c->data=6;
c->lchild=NULL;
c->rchild=NULL;
n->lchild=c;
search(p,2);
return 0;
}
4.输出所删除的结点的值 2 4 5