Print the Path Between any Two Nodes of a Tree | DFS


To print the way between any two hubs of a tree utilising Depth−First Look (DFS), we will navigate the tree and keep track of the way from the source hub to the target hub. DFS investigates the tree by going as deep as conceivable and recently backtracking. We begin DFS at the source hub and recursively visit its children. During navigation, we keep a way variable that stores the current way from the source to the current hub. In the event that we encounter the target hub amid the traversal, we print the way. This approach permits us to find and print the way between any two hubs within the tree using DFS traversal.

Methods Used

  • DFS

DFS

To print the way between any two hubs in a tree, we are able to utilise a Depth−first−look (DFS) approach. DFS begins from a chosen hub and investigates as far as conceivable along each department, recently backtracking. We begin DFS from the root hub and navigate the tree until we reach the target hub. During the traversal, we keep track of the route from the root to the current hub. Once the target hub is found, we print the putaway way. In the event that the target hub isn't found, we backtrack and proceed with investigating other branches until the target hub is experienced or all ways have been investigated. This DFS approach makes a difference in our ability to recognise and print the way between any two hubs in a tree.

Algorithm

  • Begin with the root hub of the tree.

  • Define a recursive function called printPathDFS that takes the current hub, target hub, and a vector to store the way as parameters.

  • Inside the print PathDFS function:

  • Add the current hub to the way vector.

  • Check if the current hub is the target hub. In the case of genuineness, print the vector and return.

  • Recursively call the printPathDFS work for each child hub of the current node.

  • After investigating all child hubs, evacuate the current hub from the way vector.

  • Initialise a purge vector to store the path.

  • Call the printPathDFS function, beginning from the root hub and passing the target hub and the way vector.

  • If the target hub isn't found after the DFS traversal, print a message demonstrating that the way does not exist.

Example

#include <iostream>
#include <vector>

using namespace std;

struct Element {
    int val;
    vector<Element*> children;
    Element* parent;

    Element(int value) {
        val = value;
        parent = nullptr;
    }
};

bool printPathDFS(Element* currentElement, int targetElement, vector<int>& path) {
    path.push_back(currentElement->val);

    if (currentElement->val == targetElement) {
        for (int i = 0; i < path.size(); i++) {
            cout << path[i] << " ";
        }
        cout << endl;
        return true;
    }

    for (Element* child : currentElement->children) {
        if (printPathDFS(child, targetElement, path)) {
            return true;
        }
    }

    path.pop_back();
    return false;
}

void printPathBetweenElements(Element* startElement, Element* endElement) {
    vector<int> path;

    if (startElement != nullptr && endElement != nullptr) {
        printPathDFS(startElement, endElement->val, path);
    } else {
        cout << "One or both elements not found in the tree." << endl;
    }
}

int main() {
    // Create a sample tree
    Element* root = new Element(1);
    Element* element2 = new Element(2);
    Element* element3 = new Element(3);
    Element* element4 = new Element(4);
    Element* element5 = new Element(5);
    Element* element6 = new Element(6);

    root->children.push_back(element2);
    root->children.push_back(element3);
    element2->parent = root;
    element3->parent = root;

    element2->children.push_back(element4);
    element4->parent = element2;

    element3->children.push_back(element5);
    element3->children.push_back(element6);
    element5->parent = element3;
    element6->parent = element3;

    int startElement = 21;
    int endElement = 35;

    Element* start = nullptr;
    Element* end = nullptr;

    // Find the start and end elements in the tree
    for (Element* child : root->children) {
        if (child->val == startElement) {
            start = child;
        }
        if (child->val == endElement) {
            end = child;
        }
    }

    printPathBetweenElements(start, end);

    return 0;
}

Output

One or both elements not found in the tree.

Conclusion

This article is almost printing the way between any two hubs of a tree utilising the Depth−First Look (DFS) approach. The DFS calculation is clarified in detail, laying out the steps included in navigating the tree and finding the way. The code execution in C is given, displaying the adjusted TreeNode structure and the capacities for DFS traversal and printing the way. The article concludes by illustrating the yield of the programme and emphasising the convenience of DFS in recognising and printing ways between hubs in a tree.

Updated on: 14-Jul-2023

395 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements