Node having maximum number of nodes less than its value in its subtree

Given a Binary Tree, the task is to find the node from the given tree which has the maximum number of nodes in its subtree with values less than the value of that node. In the case of multiple possible nodes with the same number of maximum nodes, then return any such node.

Examples:

Input:

           4
       /      \
     6       10
  /  \      /   \
2    3   7     14
    /
   5 
  
Output: 6
Explanation:
Node with value 6 has the maximum of nodes which are less than 6 in the subtree of 6 as (2, 3, 5) i.e., 3.

Input: 
         10
       /    
    21 
  /  \   
2    4 
        \
        11



Output: 21
Explanation:
Node with value 21 has the maximum of nodes which are less than 21 in the subtree of 21 as (2, 4, 11) i.e., 3.

Approach: The idea is to use the Post Order traversal. Below are the steps:

  1. Perform the Post Order Traversal on the given tree.
  2. Compare the nodes from the left sub-tree and the right sub-tree to its root value and if it is less than the root’s value and store the nodes which are less than the root node.
  3. Using the above step at each Node, find the number of nodes, then choose the node that has the maximum number of nodes whose keys are less than the current node.
  4. After the above traversal print that node having the maximum count of lesser node value than that nodes.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Stores the nodes to be deleted
unordered_map<int, bool> mp;
  
// Structure of a Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
  
// Function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
  
// Function to compare the current node
// key with keys received from it left
// & right tree by Post Order traversal
vector<int> findNodes(Node* root, int& max_v,
                      int& rootIndex)
{
    // Base Case
    if (!root) {
        return vector<int>{};
    }
  
    // Find nodes lesser than the current
    // root in the left subtree
    vector<int> left
        = findNodes(root->left, max_v,
                    rootIndex);
  
    // Find nodes lesser than the current
    // root in the right subtree
    vector<int> right
        = findNodes(root->right, max_v,
                    rootIndex);
  
    // Stores all the nodes less than
    // the current node's
    vector<int> combined;
    int count = 0;
  
    // Add the nodes which are less
    // than current node in left[]
    for (int i = 0;
         i < left.size(); i++) {
  
        if (left[i] < root->key) {
            count += 1;
        }
        combined.push_back(left[i]);
    }
  
    // Add the nodes which are less
    // than current node in right[]
    for (int i = 0;
         i < right.size(); i++) {
  
        if (right[i] < root->key) {
            count += 1;
        }
        combined.push_back(right[i]);
    }
  
    // Create a combined vector for
    // pass to it's parent
    combined.push_back(root->key);
  
    // Stores key that has maximum nodes
    if (count > max_v) {
        rootIndex = root->key;
        max_v = count;
    }
  
    // Return the vector of nodes
    return combined;
}
  
// Driver Code
int main()
{
    /*
              3
           /     \
           4        6
         /  \     /   \
       10    2   4     5
    */
  
    // Given Tree
    Node* root = newNode(3);
    root->left = newNode(4);
    root->right = newNode(6);
    root->right->left = newNode(4);
    root->right->right = newNode(5);
    root->left->left = newNode(10);
    root->left->right = newNode(2);
  
    int max_v = 0;
    int rootIndex = -1;
  
    // Function Call
    findNodes(root, max_v, rootIndex);
  
    // Print the node value
    cout << rootIndex;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for 
// the above approach
import java.util.*;
class GFG{
  
// Stores the nodes to be deleted
static HashMap<Integer,
               Boolean> mp = new HashMap<Integer,
                                         Boolean>();
static int max_v, rootIndex;
// Structure of a Tree node
static class Node 
{
  int key;
  Node left, right;
};
  
// Function to create a new node
static Node newNode(int key)
{
  Node temp = new Node();
  temp.key = key;
  temp.left = temp.right = null;
  return (temp);
}
  
// Function to compare the current node
// key with keys received from it left
// & right tree by Post Order traversal
static Vector<Integer> findNodes(Node root)
{
  // Base Case
  if (root == null
  {
    return new Vector<Integer>();
  }
  
  // Find nodes lesser than the current
  // root in the left subtree
  Vector<Integer> left = findNodes(root.left);
  
  // Find nodes lesser than the current
  // root in the right subtree
  Vector<Integer> right = findNodes(root.right);
  
  // Stores all the nodes less than
  // the current node's
  Vector<Integer> combined = new Vector<Integer>();
  int count = 0;
  
  // Add the nodes which are less
  // than current node in left[]
  for (int i = 0; i < left.size(); i++) 
  {
    if (left.get(i) < root.key) 
    {
      count += 1;
    }
    combined.add(left.get(i));
  }
  
  // Add the nodes which are less
  // than current node in right[]
  for (int i = 0; i < right.size(); i++) 
  {
    if (right.get(i) < root.key) 
    {
      count += 1;
    }
    combined.add(right.get(i));
  }
  
  // Create a combined vector for
  // pass to it's parent
  combined.add(root.key);
  
  // Stores key that has maximum nodes
  if (count > max_v) 
  {
    rootIndex = root.key;
    max_v = count;
  }
  
  // Return the vector of nodes
  return combined;
}
  
// Driver Code
public static void main(String[] args)
{
  /*
              3
           /     \
          4       6
         /  \    /  \
       10    2  4    5
    */
  
  // Given Tree
  Node root = newNode(3);
  root.left = newNode(4);
  root.right = newNode(6);
  root.right.left = newNode(4);
  root.right.right = newNode(5);
  root.left.left = newNode(10);
  root.left.right = newNode(2);
  
  max_v = 0;
  rootIndex = -1;
  
  // Function Call
  findNodes(root);
  
  // Print the node value
  System.out.print(rootIndex);
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for 
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Stores the nodes to be deleted
static Dictionary<int,
                  Boolean> mp = new Dictionary<int,
                                               Boolean>();
static int max_v, rootIndex;
  
// Structure of a Tree node
class Node 
{
    public int key;
    public Node left, right;
};
  
// Function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
  
// Function to compare the current node
// key with keys received from it left
// & right tree by Post Order traversal
static List<int> findNodes(Node root)
{
      
    // Base Case
    if (root == null
    {
        return new List<int>();
    }
      
    // Find nodes lesser than the current
    // root in the left subtree
    List<int> left = findNodes(root.left);
      
    // Find nodes lesser than the current
    // root in the right subtree
    List<int> right = findNodes(root.right);
      
    // Stores all the nodes less than
    // the current node's
    List<int> combined = new List<int>();
    int count = 0;
      
    // Add the nodes which are less
    // than current node in []left
    for(int i = 0; i < left.Count; i++) 
    {
        if (left[i] < root.key) 
        {
            count += 1;
        }
        combined.Add(left[i]);
    }
      
    // Add the nodes which are less
    // than current node in []right
    for(int i = 0; i < right.Count; i++) 
    {
        if (right[i] < root.key) 
        {
            count += 1;
        }
        combined.Add(right[i]);
    }
      
    // Create a combined vector for
    // pass to it's parent
    combined.Add(root.key);
      
    // Stores key that has maximum nodes
    if (count > max_v) 
    {
        rootIndex = root.key;
        max_v = count;
    }
      
    // Return the vector of nodes
    return combined;
}
  
// Driver Code
public static void Main(String[] args)
{
    /*
               3
            /     \
           4      6
          / \    / \
        10   2  4   5
        */
      
    // Given Tree
    Node root = newNode(3);
    root.left = newNode(4);
    root.right = newNode(6);
    root.right.left = newNode(4);
    root.right.right = newNode(5);
    root.left.left = newNode(10);
    root.left.right = newNode(2);
      
    max_v = 0;
    rootIndex = -1;
      
    // Function call
    findNodes(root);
      
    // Print the node value
    Console.Write(rootIndex);
}
}
  
// This code is contributed by Amit Katiyar

chevron_right


Output: 

6

Time Complexity: O(N2)
Auxiliary Space: O(N)

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.




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 : Rajput-Ji, amit143katiyar