c - 树/链表结构的遍历

标签 c data-structures linked-list binary-search-tree traversal

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/

相关文章:

我可以在c中创建这种链表吗?

c++ - 链表 - 移动到下一个节点

常见的 pre-C89 编译器/stdlib 习语(1985-1988)

c - 这个递归函数如何返回一个值给main?

c# - 我应该使用什么数据结构来表示多对一映射?

python - BST 还是哈希表?

c - 为什么我可以在声明前使用结构类型的指针

传递给函数的参数损坏

algorithm - 找出唯一的最长公共(public)子序列的数量

java - 如何从对象的 LinkedList 以及所有这些对象的 LinkedList 中删除对象?