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:
- Find path from root node to the nodes A and B, respectively and simultaneously store the two paths in two arrays.
- Now iterate until values of both the arrays are same and value just before mismatch is the LCA node value.
- The value just before mismatch is the LCA node value.
- 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)
- Return the sum of those distances i.e dist (LCA, A) + dist (LCA, B).
Time complexity: O(N).
Auxiliary Space: O(N).