天天看點

王道課後習題4.3.11:對于樹中每一個元素值為x的結點,删去以它為根的子樹,并釋放相應的空間

void del_x(TNode* p)
{
    if(p!=NULL)
    {
        del_x(p->lchild);
        del_x(p->rchild);
        free(p);//最後釋放根
    }
}
int del_x_Q(TNode* p,char x)
{
    Queue Q;
    InitQueue(Q);
    if(p==NULL)
        return 0;
    if(p->data==x)
    {
        del_x(p);
        return 0;
    }
    EnQueue(Q,p);
    while(QueueEmpty(Q)!=true)
    {
        DeQueue(Q,p);
        if(p->lchild!=NULL)
        {
            if(p->lchild->data==x)
            {
                del_x(p->lchild);
                p->lchild=NULL;
            }
            else
                EnQueue(Q,p->lchild);
        }
       if(p->rchild!=NULL)
       {
            if(p->rchild->data==x)
            {
                del_x(p->rchild);
                p->rchild=NULL;
            }
            else
                EnQueue(Q,p->rchild);
       }
    }
}

           

繼續閱讀