Given a Binary Tree of distinct nodes and a pair of nodes. The task is to find and print the path between the two given nodes in the binary tree.
For Example, in the above binary tree the path between the nodes 7 and 4 is 7 -> 3 -> 1 -> 4.
The idea is to find paths form root nodes to the two nodes and store them in two separate vectors or arrays say path1 and path2.
Now, there arises two different cases:
- If the two nodes are in different subtrees of root nodes. That is one in the left subtree and the other in the right subtree. In this case it is clear that root node will lie in between the path from node1 to node2. So, print path1 in reverse order and then path 2.
- If the nodes are in the same subtree. That is either in the left subtree or in the right subtree. In this case you need to observe that path from root to the two nodes will have an intersection point before which the path is common for the two nodes from the root node. Find that intersection point and print nodes from that point in a similar fashion of the above case.
Below is the implementation of the above approach:
7 3 1 4
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 path between any two nodes in a Binary Tree | Set 2
- XOR of path between any two nodes in a Binary Tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Sum of all odd nodes in the path connecting two given nodes
- Count of 1's in any path in a Binary Tree
- Minimum sum path between two leaves of a binary tree
- Maximum absolute difference between any two level sum in a Binary Tree
- Least Common Ancestor of any number of nodes in Binary Tree
- Queries to find distance between two nodes of a Binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Shortest distance between two nodes in an infinite binary tree
- Find distance between two nodes in the given Binary tree for Q queries
- Print the longest leaf to leaf path in a Binary tree
- Print the first shortest root to leaf path in a Binary Tree
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Print all Coprime path of a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Print nodes in top view of Binary Tree | Set 2
- Print the nodes of Binary Tree having a grandchild
- Print all even nodes of Binary Search Tree
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.