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.
- Print common nodes on path from root (or common ancestors)
- Print all root-to-leaf paths with maximum count of even nodes
- Print path from root to all nodes in a Complete Binary Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Remove nodes on root to leaf paths of length < K
- Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Print root to leaf paths without using recursion
- Print all root to leaf paths with there relative positions
- Print all the paths from root, with a specified sum in Binary tree
- Find the path from root to the given nodes of a tree for multiple queries
- Sum of nodes in the path from root to N-th node in given Tree
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- Print path from root to a given node in a binary tree
- Sum of all odd nodes in the path connecting two given nodes
- Sum of Nodes and respective Neighbors on the path from root to a vertex V
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U