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
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.
- Sum of all odd nodes in the path connecting two given nodes
- Find triplet such that number of nodes connecting these triplets is maximum
- Diameters for each node of Tree after connecting it with given disconnected component
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Shortest path between two nodes in array like representation of binary tree
- XOR of path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Sum of nodes in the path from root to N-th node in given Tree
- Find the maximum path sum between two leaves of a binary tree
- Minimum sum path between two leaves of a binary tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Distance between two nodes of binary tree with node values from 1 to N
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Print path from root to all nodes in a Complete Binary Tree
- Count nodes having smallest value in the path from root to itself in a Binary Tree
- Count nodes having highest value in the path from root to itself in a Binary Tree
- Query to find the maximum and minimum weight between two nodes in the given tree using LCA.
- Print the path between any two nodes of a tree | DFS
- Queries to check if the path between two nodes in a tree is a palindrome
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.