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.

Examples:

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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Structure of binary tree
struct Node {
    Node* left;
    Node* right;
    int data;
};
  
// Function to create a new node
Node* newNode(int key)
{
    Node* node = new Node();
    node->left = node->right = NULL;
    node->data = key;
    return node;
}
  
// Function to store the path from root node
// to given node of the tree in path vector and
// then returns true if the path exists
// otherwise false
bool FindPath(Node* root, vector<int>& path, int key)
{
    if (root == NULL)
        return false;
  
    path.push_back(root->data);
  
    if (root->data == key)
        return true;
  
    if (FindPath(root->left, path, key)
        || FindPath(root->right, path, key))
        return true;
  
    path.pop_back();
    return false;
}
  
// Function to print the minimum and the maximum
// value present in the path connecting the
// given two nodes of the given binary tree
int minMaxNodeInPath(Node* root, int a, int b)
{
  
    // To store the path from the root node to a
    vector<int> Path1;
  
    // To store the path from the root node to b
    vector<int> Path2;
  
    // To store the minimum and the maximum value
    // in the path from LCA to a
    int min1 = INT_MAX;
    int max1 = INT_MIN;
  
    // To store the minimum and the maximum value
    // in the path from LCA to b
    int min2 = INT_MAX;
    int max2 = INT_MIN;
  
    int i = 0;
    int j = 0;
  
    // If both a and b are present in the tree
    if (FindPath(root, Path1, a) && FindPath(root, Path2, b)) {
  
        // Compare the paths to get the first different value
        for (i = 0; i < Path1.size() && Path2.size(); i++)
            if (Path1[i] != Path2[i])
                break;
  
        i--;
        j = i;
  
        // Find minimum and maximum value
        // in the path from LCA to a
        for (; i < Path1.size(); i++) {
            if (min1 > Path1[i])
                min1 = Path1[i];
            if (max1 < Path1[i])
                max1 = Path1[i];
        }
  
        // Find minimum and maximum value
        // in the path from LCA to b
        for (; j < Path2.size(); j++) {
            if (min2 > Path2[j])
                min2 = Path2[j];
            if (max2 < Path2[j])
                max2 = Path2[j];
        }
  
        // Minimum of min values in first
        // path and second path
        cout << "Min = " << min(min1, min2) << endl;
  
        // Maximum of max values in first
        // path and second path
        cout << "Max = " << max(max1, max2);
    }
  
    // If no path exists
    else
        cout << "Min = -1\nMax = -1";
}
  
// Driver Code
int main()
{
    Node* root = newNode(20);
    root->left = newNode(8);
    root->right = newNode(22);
    root->left->left = newNode(5);
    root->left->right = newNode(3);
    root->right->left = newNode(4);
    root->right->right = newNode(25);
    root->left->right->left = newNode(10);
    root->left->right->right = newNode(14);
  
    int a = 5;
    int b = 1454;
  
    minMaxNodeInPath(root, a, b);
  
    return 0;
}

chevron_right


Python3

# Python3 implementation of the approach

class Node:

def __init__(self, key):
self.data = key
self.left = None
self.right = None

# Function to store the path from root
# node to given node of the tree in
# path vector and then returns true if
# the path exists otherwise false
def FindPath(root, path, key):

if root == None:
return False

path.append(root.data)

if root.data == key:
return True

if (FindPath(root.left, path, key) or
FindPath(root.right, path, key)):
return True

path.pop()
return False

# Function to print the minimum and the
# maximum value present in the path
# connecting the given two nodes of the
# given binary tree
def minMaxNodeInPath(root, a, b):

# To store the path from the
# root node to a
Path1 = []

# To store the path from the
# root node to b
Path2 = []

# To store the minimum and the maximum
# value in the path from LCA to a
min1, max1 = float(‘inf’), float(‘-inf’)

# To store the minimum and the maximum
# value in the path from LCA to b
min2, max2 = float(‘inf’), float(‘-inf’)

i, j = 0, 0

# If both a and b are present in the tree
if (FindPath(root, Path1, a) and
FindPath(root, Path2, b)):

# Compare the paths to get the
# first different value
while i < len(Path1) and i < len(Path2): if Path1[i] != Path2[i]: break i += 1 i -= 1 j = i # Find minimum and maximum value # in the path from LCA to a while i < len(Path1): if min1 > Path1[i]:
min1 = Path1[i]
if max1 < Path1[i]: max1 = Path1[i] i += 1 # Find minimum and maximum value # in the path from LCA to b while j < len(Path2): if min2 > Path2[j]:
min2 = Path2[j]
if max2 < Path2[j]: max2 = Path2[j] j += 1 # Minimum of min values in first # path and second path print("Min =", min(min1, min2)) # Maximum of max values in first # path and second path print("Max =", max(max1, max2)) # If no path exists else: print("Min = -1\nMax = -1") # Driver Code if __name__ == "__main__": root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(5) root.left.right = Node(3) root.right.left = Node(4) root.right.right = Node(25) root.left.right.left = Node(10) root.left.right.right = Node(14) a, b = 5, 14 minMaxNodeInPath(root, a, b) # This code is contributed by Rituraj Jain [tabbyending]

Output:

Min = 3
Max = 14


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.



Improved By : rituraj_jain