无法使我的删除和DFS功能正常工作

时间:2014-02-27 05:48:51

标签: c depth-first-search

我正在尝试创建一个Tree数据结构,用于存储有关奥运场馆的信息。我刚遇到障碍,我意识到我的删除功能总是返回“未找到元素”,我的DFS将找到正确的节点,但随后继续打印出树的右侧。

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;
}

1 个答案:

答案 0 :(得分:0)

  1. 请尝试preorder_find()

    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)
        {   
            if ((temp = preorder_find(find_city, T->Left))
                    || (temp = preorder_find(find_city, T->Right)))
                return temp;
        }
    
    }
    
    
    return T;
    

    }

  2.   

    我的删除功能总是返回“找不到元素”

    根据您的delete(),这意味着T的{​​{1}}参数始终为delete()