节点代码或算法的泛型树父

Generic Tree father of a node code or algorithm

本文关键字:泛型 算法 代码 节点      更新时间:2023-10-16

我有一个任务,要求我从txt中读取一个通用树,在内存中分配树,然后执行一系列操作,如删除节点、删除子树、列出节点的子节点、列出节点子节点,以及我遇到的问题,列出节点的父节点。所使用的语言是C。C++语言中可能有一些元素不是"快捷键",例如使用类。

我使用这个结构作为通用树:

typedef struct genTree
    {
        char info;
        struct genTree* first; //points to the first child of a node
        struct genTree* next; //points to the first sibling of a node
    }tgt;
    typedef tgt* pgt;

这意味着一个节点的父亲指向它的第一个孩子,然后这个孩子指向它的兄弟姐妹。

我想出了一个总是返回树根的函数:

pgt find_father(pgt root, char SON_PARAM)    
{    
        pgt son, father;
        if(root == NULL) return NULL;
        if(root->info == SON_NODE) return root;
        if(root->next != NULL) {
             son = find_father(root->next, SON_NODE);
             return son;
        }
        else {
             father = root;
             son = find_father(root->first, SON_NODE);
             if(son == NULL) return NULL;
             else return son;
        }
}

感谢您的帮助。

函数并不是在所有情况下都有返回语句。您应该返回struct genTree *类型的内容。此外,当您设置b->first = find_father(root->next, NODE_PARAM)时,您实际上覆盖了整个树。请记住,b不是struct genTree,而是struct genTree *。这意味着您正在重置b指向的内容中的字段first。最后,您必须在此处进行深度优先搜索,因为您没有反向引用。最简单的方法是在struct genTree中引入反向引用。假设我理解你试图正确地做什么,试试这个:

struct genTree
{
    char info;
    struct genTree* parent; //points to the parent of a node (NULL if root)
    struct genTree* first; //points to the first child of a node
    struct genTree* next; //points to the first sibling of a node
}
struct genTree* find_father(struct genTree* root, char NODE_PARAM)    
{    
        struct genTree* b;
        if(root == NULL) return NULL;  //standard error checking    
        if(root->info == NODE_PARAM) return root->parent;    
        b = find_father(root->first, NODE_PARAM);
        if(b == NULL)     
        {    
            b = find_father(root->next, NODE_PARAM);
        }
        return b;
}

在这种情况下,退出代码1可能是由于处理器试图读取垃圾返回值而导致的。如果它是一个数字,这是可以的,但垃圾指针(即使它只是NULL)通常是个问题。