Print path between any two nodes in a Binary Tree | Set 2
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.
Input: N1 = 7, N2 = 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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Output: 7 3 1 4
Approach: An approach to solve this problem has been discussed in this article. In this article, an even optimized recursive approach will be discussed.
In this recursive approach, below are the steps:
- Find the first value recursively, once found add the value to the stack.
- Now every node that is visited whether in backtracking or forward tracking, adds the values to the stack but if the node was added in the forward tracking then remove it in the backtracking and continue this until the second value is found or all nodes are visited.
For example: Consider the path between 7 and 9 is to be found in the above tree. We traverse the tree as DFS, once we find the value 7, we add it to the stack. Traversing path 0 -> 1 -> 3 -> 7.
Now while backtracking, add 3 and 1 to the stack. So as of now, the stack has [7, 3, 1], child 1 has a right child, so we first add it to the stack. Now, the stack contains [7, 3, 1, 4]. Visit the left child of 4, add it to the stack. The stack contains [7, 3, 1, 4, 8] now. Since there is no further node we would go back to the previous node and since 8 was already added to the stack so remove it. Now the node 4 has a right child, and we add it to the stack since this is the second value we were looking for there won’t be any further recursive calls. Finally, the stack contains [7, 3, 1, 4, 9].
Below is the implementation of the above approach:
7 3 1 4