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
- Print path from root to all nodes in a Complete Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Shortest path between two nodes in array like representation of binary tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- 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 all nodes between two given levels in Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Print all even nodes of Binary Search Tree
- Print all internal nodes of a Binary tree
- Print Nodes in Top View of Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print Levels of all nodes in a Binary Tree
- Print all nodes in a binary tree having K leaves
- Print all full nodes in a Binary 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 email@example.com. 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.