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
Output: 7 3 1 4
Approach: An approach to solve this problem has been discussed in this article. In this article, an even optimised 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, add 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
- Print path between any two nodes in a Binary Tree
- 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 internal nodes of a Binary tree
- Print Levels of all nodes in a Binary Tree
- Print Nodes in Top View of Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print all full nodes 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
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.