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.
- Print common nodes on path from root (or common ancestors)
- Print path from root to all nodes in a Complete Binary Tree
- Remove nodes on root to leaf paths of length < K
- Print root to leaf paths without using recursion
- Print all the paths from root, with a specified sum in Binary tree
- Print all root to leaf paths with there relative positions
- Given a binary tree, print all root-to-leaf paths
- Sum of nodes on the longest path from root to leaf node
- Root to leaf path with maximum distinct nodes
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Print path from root to a given node in a binary tree
- Print the first shortest root to leaf path in a Binary Tree
- Print nodes at k distance from root
- Print nodes at k distance from root | Iterative
- Print path between any two nodes in a Binary Tree