给出以下结构
struct nNode {
int val;
struct nNode parent;
struct nNode children;
struct nNode next;
struct nNode prev;
};
如果children
指向第一个孩子并且要遍历其他孩子,我们需要关注node->children->next
...
我尝试使用函数返回指向包含某些val
的元素的指针
struct nNode* nNode_find(struct nNode *node, int val)
{
// We found the node return the pointer
if(node->val == val) return node;
// We didn't found let's check the children
struct nNode *child = node->children;
while(child) {
nNode_find(child, val);
child = child->children;
// We didn't found on child, lets check his brothers
struct nNode *sibling = child->next;
while(sibling) {
nNode_find(sibling, val);
sibling = sibling->next;
}
}
// We didn't found the element return NULL
return NULL;
}
给定树TREE
,如:
/* 1
* /---------|--------\
* 2 3 4
* / \ /
* 5 6 7
*/
像
这样的命令struct nNode *ptr = nNode_find(TREE, 3);
应返回指向root->children->next
的指针,但实际nNode_find
正在返回NULL
。
答案 0 :(得分:1)
问题是你忽略了递归nNode_find
的返回值。如果返回的值为非NULL,则应该直接返回。而不是
nNode_find(child, val);
做
struct nNode* found = nNode_find(child, val);
if (found) {
return found;
}
此外,每个nNode_find
调用应该只处理一个节点,而不是下降到儿童的子节点,或者等等;你想做一些调试打印,以确保每个节点最多只搜索一次。