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
- Minimum sum path between two leaves of a binary tree
- Find the maximum path sum 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
- Query to find the maximum and minimum weight between two nodes in the given tree using LCA.
- 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
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Maximum sum of nodes in Binary tree such that no two are adjacent
- Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming
- Maximum length cycle that can be formed by joining two nodes of a binary tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL 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 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.