Search code examples
cdata-structureslinked-listbinary-search-treetraversal

Traversal in tree/linked list structure


This is what my structure looks like

It is kind of like a hybrid tree/linked list structure. Here's how I defined the structure

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

a node has a child, that is connected to a linked list. Other elements on the linked list may have their own child that is connected to the linked list or by itself

Now to my question, how would I traverse this structure to search and print the path to a specific node.

Any suggestions would be appreciated. Thanks

Update Here is printPath function:

//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);
    }
}

My problem is getting out of the recursive call, once if finish printing path to the current node.


Solution

  • The node structure presented in the question is the same as for a regular binary tree which is using names child and sibling instead of the traditional left and right. If you want to print a path to the desired node, you should print the root values of each subtree containing that node. So here is the pseudocode:

    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 
    

    Here, if root is null, it is not containing the desired node, so we return false for this path printing nothing. But if it's name is the one that we want, or one of it's subtrees is containing what we want, we print the name and returning true. This way you will get the path printed in the order from the leaf to root.