给定二叉树,删除结点值为x的左右子树
利用层次遍历找到结点值为x的左右子树,分别删除;
删除算法
void Delete(Tree &T) { if(T) { Delete(T->lchild); Delete(T->rchild); free(T); } }
完整算法
#include <stdio.h> #include <stdlib.h> #define MaxSize 100 typedef struct node{ int data; struct node *lchild,*rchild; }TreeNode,*Tree; typedef TreeNode* Elem; typedef struct{ Elem data[MaxSize]; int front; int rear; }Queue; void InitQueue(Queue &Q) { Q.front=Q.rear=0; } bool isEmpty(Queue Q) { if(Q.front==Q.rear) return true; else return false; } bool isFull(Queue Q) { if((Q.rear+1)%MaxSize==Q.front) return true; else return false; } bool EnQueue(Queue &Q,Elem p) { if(isFull(Q)) return false; Q.data[Q.rear]=p; Q.rear=(Q.rear+1)%MaxSize; return true; } bool DeQueue(Queue &Q,Elem &p) { if(isEmpty(Q)) return false; p=Q.data[Q.front]; Q.front=(Q.front+1)%MaxSize; return true; } void CreateTree(Tree &T) { int x; scanf("%d",&x); if(x==-1) { T=NULL; return; } else { T=(TreeNode*)malloc(sizeof(TreeNode)); T->data=x; printf("输入%d的左结点:",x); CreateTree(T->lchild); printf("输入%d的右结点:",x); CreateTree(T->rchild); } } void Delete(Tree &T) { if(T) { Delete(T->lchild); Delete(T->rchild); free(T); } } void Select(Tree &T,int x) { if(T->data==x) { Delete(T); return; } TreeNode *p=T; Queue Q; InitQueue(Q); EnQueue(Q,p); while(!isEmpty(Q)) { DeQueue(Q,p); if(p->lchild) { if(p->lchild->data==x) { Delete(p->lchild); p->lchild=NULL; } } if(p->rchild) { if(p->rchild->data==x) { Delete(p->rchild); p->rchild=NULL; } } } } void PreOrder(Tree T) { if(T==NULL) return; else { printf("%d ",T->data); PreOrder(T->lchild); PreOrder(T->rchild); } } int main() { Tree T; CreateTree(T); PreOrder(T); printf("\n"); Select(T,2); PreOrder(T); return 0; }
标签:11,lchild,144,return,Tree,rchild,data,Delete From: https://www.cnblogs.com/simpleset/p/17758337.html