Print path between any two nodes in a Binary Tree
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 from 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
- Time Complexity: O(N), as we are using recursion for traversing the tree. Where N is the number of nodes in the tree.
- Auxiliary Space: O(N), as we are using extra space for storing the paths of the trees. Where N is the number of nodes in the tree.
My Personal Notes arrow_drop_up
Please Login to comment...