Given a binary tree with distinct nodes(no two nodes have the same have data values). The problem is to print the path common to the two paths from the root to the two given nodes n1 and n2. If either of the nodes are not present then print “No Common Path”.
Input : 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 n1 = 4, n2 = 8 Output : 1->2 Path form root to n1: 1->2->4 Path form root to n2: 1->2->5->8 Common Path: 1->2
Approach:The following steps are:
- Find the LCA(Lowest Common Ancestor) of the two nodes n1 and n2. Refer this.
- If LCA exits then print the path from the root to LCA. Refer this. Else print “No Common Path”.
Time complexity: O(n), where n is the number of nodes in the binary tree.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.