VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-the-path-between-any-two-nodes-of-a-tree-dfs/

⇱ Print the path between any two nodes of a tree | DFS - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print the path between any two nodes of a tree | DFS

Last Updated : 12 Jul, 2025

Given a tree of distinct nodes N with N-1 edges and a pair of nodes P. The task is to find and print the path between the two given nodes of the tree using DFS.

Input: N = 10
1
/ \
2 3
/ | \ / | \
4 5 6 7 8 9
Pair = {4, 8}
Output: 4 -> 2 -> 1 -> 3 -> 8

Input: N = 3
1
/ \
2 3
Pair = {2, 3}
Output: 2 -> 1 -> 3


👁 Image


For example, in the above tree the path between nodes 5 and 3 is 5 -> 2 -> 1 -> 3
Path between nodes 4 and 8 is 4 -> 2 -> 1 -> 3 -> 8.

Approach:

  • The idea is to run DFS from the source node and push the traversed nodes into a stack till the destination node is traversed.
  • Whenever backtracking occurs pop the node from the stack.

Note: There should be a path between the given pair of nodes.

Below is the implementation of the above approach:  


Output
4 -> 2 -> 1 -> 3 -> 8

Efficient Approach :

In this approach we will utilise the concept of (LCA).

1. We will find level and parent of every node using DFS.

2. We will find lowest common ancestor (LCA) of the two given nodes.

3. Starting from the first node we will travel to the LCA and keep on pushing

the intermediates nodes in our path vector.

4. Then, from the second node we will again travel to the LCA but this time

we will reverse the encountered intermediate nodes and then push them in

our path vector.

5. Finally, print the path vector to get the path between the two nodes.


Output
4 -> 3 -> 2 -> 1 -> 7

Time Complexity : O(N) 

Space Complexity : O(N)

Comment
Article Tags:
Article Tags: