gpt4 book ai didi

c - 树/链表结构的遍历

转载 作者:行者123 更新时间:2023-11-30 17:21:14 27 4
gpt4 key购买 nike

This is what my structure looks like

它有点像混合树/链表结构。这是我定义结构的方式

struct node {
nodeP sibling;
nodeP child;
nodeP parent;
char name[100];
};

一个节点有一个子节点,它连接到一个链表。链表上的其他元素可能有自己的子元素,该子元素连接到链表或单独连接

现在我的问题是,我将如何遍历这个结构来搜索并打印到特定节点的路径。

如有任何建议,我们将不胜感激。谢谢

更新这是 printPath 函数:

//node -> root of the tree
//current = this is the node that i need to print path to

void printPath(nodeP node, nodeP current){

if (node != NULL){
if ((strcmp(node->name, current->name) == 0))
{
printf("%s/", node->name);
return; //it returns to the previous recursive call and then continues until the node is null
}
printPath(root->childDir, currentDir);
printPath(root->sibling, currentDir);
printf(" %s/", node->name);
}
}

我的问题是一旦完成打印当前节点的路径,就退出递归调用。

最佳答案

问题中提出的节点结构与常规二叉树相同,它使用名称 childsibling 而不是传统的 left。如果要打印所需节点的路径,则应打印包含该节点的每个子树root值。所以这是伪代码:

function printPath(root, searchName)
if root is null
return false
if root.name is searchName or
printPath(root.child, searchName) or
printPath(root.sibling, searchName) then
print root.name
return true
else
return false

这里,如果 root 为 null,则它不包含所需的节点,因此我们返回 false,因为该路径不打印任何内容。但是,如果它的名称是我们想要的名称,或者它的子树之一包含我们想要的名称,我们将打印该名称并返回 true。这样您就可以按照从叶到根的顺序打印路径。

关于c - 树/链表结构的遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28350459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com