Chris Ridgely
Chris Ridgely

Reputation: 3

Having trouble getting my Delete and DFS function to work properly

I am trying to create a Tree data structure which stores information about the Olympic Venues. I have just run into a roadblock and I have realized that my delete function always returns "Element Not Found" and my DFS will find the correct node, but then continue to print out the right side of the tree.

Tree * preorder_find(char * find_city, Tree* T)
{
    if(T)
    {

        //if(strcmp(T->Element->city, find_city) == 0)
        //return T;

        printf("%s, %s ... %d\n", T->Element->city, T->Element->country, 
                                                T->Element->year);

        if(strcmp(T->Element->city, find_city) != 0)
        {   
            preorder_find(find_city, T->Left);

            preorder_find(find_city, T->Right);
        }

    }


return T;

}



Tree* delete(char * venue, Tree* T)
{
    Tree* tmp_node;

    if(T==NULL)
        fprintf(stderr, "Element not Found\n");
    else
    if(strcmp(venue, T->Element->city) < 0)
        T->Left = delete(venue, T->Left);
    else
    if(strcmp(venue, T->Element->city) > 0)
        T->Right = delete(venue, T->Left);
    else
    if(T->Left && T->Right)
    {
        tmp_node = find_min(T->Right);
        T->Element = tmp_node->Element;
        T->Right = delete(T->Element->city, T->Right);
    }
    else
    {
        tmp_node = T;
        if(T->Left == NULL)
            T = T->Right;
        else if(T->Right == NULL)
            T = T->Left;
        free(tmp_node);
     }

     return T;
}

Upvotes: 0

Views: 49

Answers (1)

Lee Duhem
Lee Duhem

Reputation: 15121

  1. Please try this preorder_find()

    Tree * preorder_find(char * find_city, Tree* T) { Tree *temp;

    if(T)
    {
    
        if(strcmp(T->Element->city, find_city) == 0)
            return T;
    
        printf("%s, %s ... %d\n", T->Element->city, T->Element->country, 
                T->Element->year);
    
        if(strcmp(T->Element->city, find_city) != 0)
        {   
            if ((temp = preorder_find(find_city, T->Left))
                    || (temp = preorder_find(find_city, T->Right)))
                return temp;
        }
    
    }
    
    
    return T;
    

    }

  2. my delete function always returns "Element Not Found"

    According to your delete(), this means the argument T of delete() always is NULL.

Upvotes: 0

Related Questions