Open In App

Find Mode in Binary Search tree

Last Updated : 22 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Search Tree, find the mode of the tree.

Note: Mode is the value of the node which has the highest frequency in the binary search tree.

Examples:

 Input:

                  100
                 /     \
             50      160
           /    \       /    \
        50   60 140   170 
Output: The mode of BST is 50
Explanation: 50 is repeated 2 times, and all other nodes occur only once. Hence, the Mode is 50.

Input:

                  10
                /     \
             5       20
                   /      \
                 20   170 
Output: The mode of BST is 20
Explanation: 20 is repeated 2 times, and all other nodes occur only once. Hence, the Mode is 20.

Approach: To solve the problem follow the below idea:

To solve this problem, we first find the in-order traversal of the BST and count the occurrences of each value in BST. We print the elements having a maximum frequency.

Steps that were to follow to implement the approach:

  • Perform inorder traversal for the BST.
  • Count the occurrences of values in a map and update the highest frequency.
  • print the elements with the highest frequency.

Below is the implementation for the above approach:

C++

// C++ program to find the median of BST
#include <bits/stdc++.h>
using namespace std;

// A binary search tree Node has data,
// pointer to left child and a
// pointer to right child
struct Node {
    int data;
    struct Node *left, *right;
};

// Function to create a new BST node
struct Node* newNode(int item)
{
    struct Node* temp = new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}

// Function to insert a new node with
// given key in BST
struct Node* insert(struct Node* node, int key)
{

    // If the tree is empty,
    // return a new node
    if (node == NULL)
        return newNode(key);

    // Otherwise, recur down the tree
    if (key < node->data)
        node->left = insert(node->left, key);
    else if (key >= node->data)
        node->right = insert(node->right, key);

    // Return the (unchanged)
    // node pointer
    return node;
}

// Function to find inorder
// traversal of a BST
void inorderTraversal(Node* root, vector<int>& inorder)
{

    // If the tree is empty,
    // return NULL
    if (root == NULL)
        return;

    // recur on left child
    inorderTraversal(root->left, inorder);

    // Push the data of node in inorder vector
    inorder.push_back(root->data);

    // recur on right child
    inorderTraversal(root->right, inorder);
}

// Function to Mode of a BST
vector<int> findMode(Node* root)
{
    vector<int> inorder;

    // Find inorder traversal of BST
    inorderTraversal(root, inorder);
    int mx = INT_MIN;
    unordered_map<int, int> mp;

    // Counting occurrences of each
    // element and updating
    // maximum frequency
    for (int i = 0; i < inorder.size(); i++) {
        mp[inorder[i]]++;
        mx = max(mp[inorder[i]], mx);
    }
    vector<int> res;

    // Pushing the elements into vector
    // with highest frequency
    for (auto it : mp) {
        if (it.second == mx)
            res.push_back(it.first);
    }
    return res;
}

// Driver's code
int main()
{

    /* Let us create following BST
                  100
               /     \
              50      160
             /  \    /  \
           50   60  140   170 */
    struct Node* root = NULL;

    root = insert(root, 50);

    insert(root, 60);
    insert(root, 50);
    insert(root, 160);
    insert(root, 170);
    insert(root, 140);
    insert(root, 100);

    // Function call
    auto r = findMode(root);

    cout << "Mode of BST is"
         << " ";
    for (auto i : r) {
        cout << i << " ";
    }

    return 0;
}

Python3

# Python program to find the mode of a BST
import sys

# A binary search tree Node has data,
# pointer to left child and a
# pointer to right child
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

# Function to insert a new node with
# given key in BST
def insert(node, key):
    
    # If the tree is empty,
    # return a new node
    if node is None:
        return Node(key)
        
    # Otherwise, recur down the tree
    if key < node.data:
        node.left = insert(node.left, key)
    else:
        node.right = insert(node.right, key)
        
    # Return the (unchanged)
    # node pointer
    return node

# Function to find inorder
# traversal of a BST
def inorderTraversal(root, inorder):
    
    # If the tree is not empty
    if root:
        
        # recur on left child
        inorderTraversal(root.left, inorder)
        
        # Push the data of node in inorder vector
        inorder.append(root.data)
        
        # recur on right child
        inorderTraversal(root.right, inorder)
        
# Function to Mode of a BST
def findMode(root):
    inorder = []
    
    # Find inorder traversal of BST
    inorderTraversal(root, inorder)
    mp = {}
    mx = -sys.maxsize - 1
    
    # Counting occurrences of each
    # element and updating
    # maximum frequency
    for i in range(len(inorder)):
        mp[inorder[i]] = mp.get(inorder[i], 0) + 1
        mx = max(mp[inorder[i]], mx)
    res = []
    
    # Pushing the elements into vector
    # with highest frequency
    for it in mp.items():
        if it[1] == mx:
            res.append(it[0])
    return res

# Driver code

''' Let us create following BST
              100
           /     \
          50      160
         /  \    /  \
       50   60  140   170 '''
root = None
root = insert(root, 50)
insert(root, 60)
insert(root, 50)
insert(root, 160)
insert(root, 170)
insert(root, 140)
insert(root, 100)

# Function call
r = findMode(root)
print("Mode of BST is ", end="")
for i in r:
    print(i, end=" ")
    
# This code is contributed by Prasad Kandekar(prasad264)

Java

// Java program to find the mode of a BST

import java.util.*;

// A binary search tree Node has data,
// pointer to left child and a
// pointer to right child
class Node {
    int data;
    Node left, right;
    // Function to create a new BST node
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}

class Main {
    // Function to insert a new node with
    // given key in BST
    public static Node insert(Node node, int key)
    {

        // If the tree is empty,
        // return a new node
        if (node == null) {
            return new Node(key);
        }

        // Otherwise, recur down the tree
        if (key < node.data) {
            node.left = insert(node.left, key);
        }
        else if (key >= node.data) {
            node.right = insert(node.right, key);
        }

        // Return the (unchanged)
        // node pointer
        return node;
    }

    // Function to find inorder
    // traversal of a BST
    public static void
    inorderTraversal(Node root, ArrayList<Integer> inorder)
    {

        // If the tree is empty,
        // return NULL
        if (root == null) {
            return;
        }

        // recur on left child
        inorderTraversal(root.left, inorder);

        // Push the data of node in inorder list
        inorder.add(root.data);

        // recur on right child
        inorderTraversal(root.right, inorder);
    }

    // Function to Mode of a BST
    public static ArrayList<Integer> findMode(Node root)
    {
        ArrayList<Integer> inorder
            = new ArrayList<Integer>();

        // Find inorder traversal of BST
        inorderTraversal(root, inorder);
        int mx = Integer.MIN_VALUE;
        HashMap<Integer, Integer> mp = new HashMap<>();

        // Counting occurrences of each
        // element and updating
        // maximum frequency
        for (int i = 0; i < inorder.size(); i++) {
            mp.put(inorder.get(i),
                   mp.getOrDefault(inorder.get(i), 0) + 1);
            mx = Math.max(mp.get(inorder.get(i)), mx);
        }
        ArrayList<Integer> res = new ArrayList<Integer>();

        // Pushing the elements into list
        // with highest frequency
        for (Map.Entry<Integer, Integer> entry :
             mp.entrySet()) {
            if (entry.getValue() == mx) {
                res.add(entry.getKey());
            }
        }
        return res;
    }

    // Driver's code
    public static void main(String[] args)
    {

        /* Let us create following BST
              100
            /     \
           50     160
           / \   /   \
          50 60 140  170 */

        Node root = null;

        root = insert(root, 50);

        insert(root, 60);
        insert(root, 50);
        insert(root, 160);
        insert(root, 170);
        insert(root, 140);
        insert(root, 100);

        // Function call
        ArrayList<Integer> r = findMode(root);

        System.out.print("Mode of BST is ");
        for (Integer i : r) {
            System.out.print(i + " ");
        }
    }
}

C#

// C# program to find the median of BST

using System;
using System.Collections.Generic;

// A binary search tree Node has data,
// pointer to left child and a
// pointer to right child
class Node {
    public int data;
    public Node left, right;
    // Constructor to create a new BST node
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

class GFG {
    // Function to insert a new node with
    // given key in BST
    static Node Insert(Node node, int key)
    {
        // If the tree is empty,
        // return a new node
        if (node == null)
            return new Node(key);
        // Otherwise, recur down the tree
        if (key < node.data)
            node.left = Insert(node.left, key);
        else if (key >= node.data)
            node.right = Insert(node.right, key);

        // Return the (unchanged)
        // node pointer
        return node;
    }

    // Function to find inorder
    // traversal of a BST
    static void InorderTraversal(Node root,
                                 List<int> inorder)
    {
        // If the tree is empty,
        // return NULL
        if (root == null)
            return;

        // recur on left child
        InorderTraversal(root.left, inorder);

        // Push the data of node in inorder list
        inorder.Add(root.data);

        // recur on right child
        InorderTraversal(root.right, inorder);
    }

    // Function to Mode of a BST
    static List<int> FindMode(Node root)
    {
        List<int> inorder = new List<int>();

        // Find inorder traversal of BST
        InorderTraversal(root, inorder);
        int mx = int.MinValue;
        Dictionary<int, int> mp
            = new Dictionary<int, int>();

        // Counting occurrences of each
        // element and updating
        // maximum frequency
        for (int i = 0; i < inorder.Count; i++) {
            if (mp.ContainsKey(inorder[i]))
                mp[inorder[i]]++;
            else
                mp.Add(inorder[i], 1);
            mx = Math.Max(mp[inorder[i]], mx);
        }
        List<int> res = new List<int>();

        // Pushing the elements into list
        // with highest frequency
        foreach(KeyValuePair<int, int> it in mp)
        {
            if (it.Value == mx)
                res.Add(it.Key);
        }
        return res;
    }

    // Driver's code
    static void Main()
    {
        /* Let us create following BST
                    100
                /       \
               50       160
              / \      /  \
             50  60   140  170 */
        Node root = null;

        root = Insert(root, 50);
        Insert(root, 60);
        Insert(root, 50);
        Insert(root, 160);
        Insert(root, 170);
        Insert(root, 140);
        Insert(root, 100);

        // Function call
        var r = FindMode(root);

        Console.Write("Mode of BST is ");
        foreach(int i in r) { Console.Write(i + " "); }
    }
}

Javascript

// A binary search tree Node has data,
// pointer to left child and a
// pointer to right child
class Node {
  constructor(key) {
    this.data = key;
    this.left = null;
    this.right = null;
  }
}

// Function to insert a new node with
// given key in BST
function insert(node, key) {
  // If the tree is empty,
  // return a new node
  if (node === null) {
    return new Node(key);
  }

  // Otherwise, recur down the tree
  if (key < node.data) {
    node.left = insert(node.left, key);
  } else {
    node.right = insert(node.right, key);
  }

  // Return the (unchanged)
  // node pointer
  return node;
}

// Function to find inorder
// traversal of a BST
function inorderTraversal(root, inorder) {
  // If the tree is not empty
  if (root !== null) {
    // recur on left child
    inorderTraversal(root.left, inorder);

    // Push the data of node in inorder vector
    inorder.push(root.data);

    // recur on right child
    inorderTraversal(root.right, inorder);
  }
}

// Function to Mode of a BST
function findMode(root) {
  let inorder = [];

  // Find inorder traversal of BST
  inorderTraversal(root, inorder);
  let mp = {};
  let mx = -Infinity;

  // Counting occurrences of each
  // element and updating
  // maximum frequency
  for (let i = 0; i < inorder.length; i++) {
    mp[inorder[i]] = (mp[inorder[i]] || 0) + 1;
    mx = Math.max(mp[inorder[i]], mx);
  }

  let res = [];

  // Pushing the elements into vector
  // with highest frequency
  for (let it in mp) {
    if (mp[it] === mx) {
      res.push(Number(it));
    }
  }
  return res;
}

// Driver code

/* Let us create following BST
          100
         /   \
        50   160
       / \   / \
      50 60 140 170 */
let root = null;
root = insert(root, 50);
insert(root, 60);
insert(root, 50);
insert(root, 160);
insert(root, 170);
insert(root, 140);
insert(root, 100);

// Function call
let r = findMode(root);
console.log("Mode of BST is " + r.join(" "));
Output

Mode of BST is 50 

Time Complexity: O(N*logN)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads