sách gpt4 ai đã đi

c - 树/链表结构的遍历

In lại 作者:行者123 更新时间:2023-11-30 17:21:14 28 4
mua khóa gpt4 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);
}
}

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

1 Câu trả lời

问题中提出的节点结构与常规二叉树相同,它使用名称 đứa trẻsibling 而不是传统的 bên trái。如果要打印所需节点的路径,则应打印包含该节点的每个子树củagốc rễ值。所以这是伪代码:

function printPath(root, searchName)
if root is null
trả về sai
if root.name is searchName or
printPath(root.child, searchName) or
printPath(root.sibling, searchName) then
print root.name
trả về đúng
khác
trả về sai

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

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

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com