Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
Given a binary tree and two nodes a and b, the task is to print the minimum and the maximum node value that lies in the path connecting the given nodes a and b. If either of the two nodes is not present in the tree then print -1 for both minimum and maximum value.
Input: 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 a = 5, b = 6 Output: Min = 1 Max = 6 Input: 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 a = 5, b = 14 Output: Min = 3 Max = 14
Approach: The idea is to find the LCA of both the nodes. Then start searching for the minimum and the maximum node in the path from LCA to the first node and then from LCA to the second node and print the minimum and the maximum of these values. In case either of the node is not present in the tree then print -1 for the minimum as well as the maximum value.
Below is the implementation of the above approach:
Min = 3 Max = 14
Time Complexity: O(N)
Auxiliary Space: O(N)