![]() |
VOOZH | about |
Given a binary tree consisting of N nodes. Find the path between the node having the lowest value to the node having the highest value. There is no restriction on the traversal, i.e. the tree can be traversed upward, bottom, left and right.
Examples:
Input: N = 8
2
/ \
1 6
/ \ \
4 21 26
/ \
5 7{(2), (1, 6), (4, 21), (26), (5), (7)}
Output: 1 -> 2 -> 6 -> 26
Explanation: The minimum value in the tree is 1, while the maximum value is 26. So the path from the minimum value, i.e. 1 to the maximum value, i.e. 26 is 1 -> 2 -> 6 -> 26. Other than that, there is no other path from the node consisting of the minimum value to the node consisting of the maximum value.Input: N = 5
10
/ \
5 20
/ \
17 25{(10), (5, 20), (), (17, 25)}
Output: 5 -> 10 -> 20 -> 25
Explanation: The lowest node is 5 and the highest node is 25. The path between these two nodes is [5, 10, 20, 25].
Approach: This can be solved with the following idea:
- The first intuition that builds up in minds is to traverse the entire binary tree and find the node with the lowest and highest values.
- Then find the lowest common ancestor of the nodes with the lowest and highest values, then print the paths from the lowest node to the highest node using the parent pointers.
- We start at the highest value node and follow its parent pointers until we reach the lowest common ancestor. Then, we print the lowest common ancestor and follow the parent pointers of the lowest value node until we reach the next lowest common ancestor.
Below are the steps involved in the implementation of the code:
1 2 6 26
Time Complexity: O(N)
Auxiliary Space: O(h)