VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-path-between-any-two-nodes-in-a-binary-tree/

⇱ Print path between any two nodes in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print path between any two nodes in a Binary Tree

Last Updated : 11 Jul, 2025

Given a Binary Tree of distinct nodes and a pair of nodes. The task is to find and print the path between the two given nodes in the binary tree.
 

👁 Image

For Example, in the above binary tree the path between the nodes 7 and 4 is 7 -> 3 -> 1 -> 4

The idea is to find paths from root nodes to the two nodes and store them in two separate vectors or arrays say path1 and path2.

Now, there arises two different cases: 

  1. If the two nodes are in different subtrees of root nodes. That is one in the left subtree and the other in the right subtree. In this case it is clear that root node will lie in between the path from node1 to node2. So, print path1 in reverse order and then path 2.
  2. If the nodes are in the same subtree. That is either in the left subtree or in the right subtree. In this case you need to observe that path from root to the two nodes will have an intersection point before which the path is common for the two nodes from the root node. Find that intersection point and print nodes from that point in a similar fashion of the above case.

Below is the implementation of the above approach: 


Output
7 3 1 4 

Complexity Analysis:

  • Time Complexity: O(N), as we are using recursion for traversing the tree. Where N is the number of nodes in the tree.
  • Auxiliary Space: O(N), as we are using extra space for storing the paths of the trees. Where N is the number of nodes in the tree.
Comment
Article Tags: