节点代码或算法的泛型树父
Generic Tree father of a node code or algorithm
我有一个任务,要求我从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)通常是个问题。
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 链表的泛型函数remove()与成员函数remove)
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何编写将要继承的泛型代码?
- C++17 如何保存泛型可调用对象以供以后使用
- 使用宏扩展的泛型:为什么指令缓存使用不当?
- C++泛型类错误,问题出在哪里?
- C++泛型类,单独实现?
- 将参数传递给泛型 lambda 时复制构造函数不正确
- 泛型枚举和其他类型的重载模板函数
- 使用泛型类型推送到堆栈时出现问题
- 可变参数泛型 lambda 和函数重载
- C++ 泛型和多态性:这种模式可行吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- Java 是否像C++模板一样具有泛型推论?
- 节点代码或算法的泛型树父
- 为什么要区分泛型算法的谓词和非谓词版本
- 如何将基于泛型迭代器的算法与基于实现的算法结合起来?