VOOZH about

URL: https://www.geeksforgeeks.org/dsa/step-by-step-shortest-path-from-source-node-to-destination-node-in-a-binary-tree/

⇱ Step by step Shortest Path from source node to destination node in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Step by step Shortest Path from source node to destination node in a Binary Tree

Last Updated : 23 Jul, 2025

Given a root of binary tree and two integers startValue and destValue denoting the starting and ending node respectively. The task is to find the shortest path from the start node to the end node and print the path in the form of directions given below. 

  1. Going from one node to its left child node is indicated by the letter 'L'.
  2. Going from one node to its right child node is indicated by the letter 'R'.
  3. To navigate from a node to its parent node, use the letter 'U'.

Examples: 

Input: root = [5, 1, 2, 3, null, 6, 4], startValue = 3, destValue = 6

              5
          /      \
       1          2
    /          /     \
  3        6         4

Output: "UURL" 
Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6.

Input: root = [2, 1], startValue = 2, destValue = 1

            2
          /
       1

Output: "L"
Explanation: The shortest path is: 2 → 1.

Approach: The simplest way to solve this problem is to use the LCA (Lowest Common Ancestor) of a binary tree. Follow the steps below to solve the given problem. 

  • Apply LCA to get a new root.
  • Get the Path from the new root to start and dest.
  • Concatenate startPath and destPath, and make sure to replace startPath's char with 'U'.

Below is the implementation of the above approach. 


Output
UURL

Time complexity: O(3N), Because three traversals are done.
Auxiliary Space: O(N)

Efficient Approach: This approach is implementation based but LCA is not used in this approach. Follow the steps below to solve the given problem.  

  • Build directions for both start and destination from the root.
  • Say we get "LLRRL" and "LRR".
  • Remove common prefix path.
  • We remove "L", and now start direction is "LRRL", and destination - "RR"
  • Replace all steps in the start direction to "U" and add the destination direction.
  • The result is "UUUU" + "RR".

Below is the implementation of the above approach.  


Output
UURL

Time complexity: O(N)
Auxiliary Space: O(N)

Comment
Article Tags: