Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

c - Problem when trying to remove a node in a tree

I have a binary tree. I'm trying to delete one of the node and all of his "children". But, my function deletes just the children and the "father" is still remaining there. whats wrong with my code? why the "father" isnt Deleted??

BinTree* familyGotVaccin(BinTree* root)
{
    int isFather = 1;
    BinTree* father = NULL;
    BinTree* gotVaccinated = NULL;
    int ID;
    if (root == NULL)
        return NULL;
    printf("Who got vaccinated (ID)?
");
    scanf("%d", &ID);
    if (checkIfExist(root, ID) == 0)
    {
        printf("There is no ID %d
", ID);
        return root;
    }
    if (root->ID == ID)
    {
        gotVaccinated = root;
        isFather=0;
    }
    else
    {
        father = findNode(root, ID);
        if (father == NULL)
            return root;
        if (father->left != NULL && father->left->ID == ID)
            gotVaccinated = father->left;
        if (father->middle != NULL && father->middle->ID == ID)
            gotVaccinated = father->middle;
        if (father->right != NULL && father->right->ID == ID)
            gotVaccinated = father->right;
    }
        gotVaccinated=deleteVaccinated(gotVaccinated);
        free(gotVaccinated);
        if (isFather == 0)
            root = NULL;
        return root;
    
}




BinTree* deleteVaccinated(BinTree* root)
{
    if (root == NULL)
        return NULL;
    if (root->left == NULL && root->middle == NULL && root->right == NULL)
    {
        printf("%s ID: %d Survived!
", root->name, root->ID);
        root = NULL;
        free(root);
        return NULL;
    }
    if (root->left != NULL)
        root->left=deleteVaccinated(root->left);
    if (root->middle != NULL)
        root->middle=deleteVaccinated(root->middle);
    if (root->right != NULL)
        root->right=deleteVaccinated(root->right);
    printf("%s ID: %d Survived!
", root->name, root->ID);
    root = NULL;
    free(root);
    return NULL;

} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...