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 firstname.lastname@example.org. 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 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
- Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
- Remove nodes on root to leaf paths of length < K
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Find the path from root to the given nodes of a tree for multiple queries
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- 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
- Sum of all odd nodes in the path connecting two given nodes
- Print path from root to a given node in a binary tree
- Sum of nodes on the longest path from root to leaf node
- Root to leaf path with maximum distinct 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
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Count the number of paths from root to leaf of a Binary tree with given XOR value