VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-distance-between-two-given-nodes-in-an-n-ary-tree/

⇱ Minimum distance between two given nodes in an N-ary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum distance between two given nodes in an N-ary tree

Last Updated : 23 Jul, 2025

Given a N ary Tree consisting of N nodes, the task is to find the minimum distance from node A to node B of the tree.

Examples:

Input:              
         1          
    /         \      
  2            3    
 /  \       /  \   \
4   5    6    7   8
A = 4, B = 3
Output: 3
Explanation: The path 4->2->1->3 gives the minimum distance from A to B.

Input:
         1          
   /         \      
2            3    
          /  \  \
       6    7   8
A = 6, B = 7
Output: 2

Approach: This problem can be solved by using concept of LCA(Lowest Common Ancestor). Minimum distance between two given nodes A and B can be found out by using formula -
mindistance(A, B) = dist (LCA, A) + dist (LCA, B)
Follow the steps below to solve the problem:

  1. Find path from root node to the nodes A and B, respectively and simultaneously store the two paths in two arrays.
  2. Now iterate until values of both the arrays are same and value just before mismatch is the LCA node value.
  3. The value just before mismatch is the LCA node value.
  4. Find distance from the LCA node to node A and B, which can be found with the given steps:
    • In first array, iterate from LCA node value and increase count until value of node A is found, which is dist (LCA, A).
    • In the second array, iterate from LCA node value and increase count until value of node B is found, which is dist (LCA, B)
  5. Return the sum of those distances i.e dist (LCA, A) + dist (LCA, B).

Output
3

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

Comment
Article Tags: