Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Inorder successor in Binary Tree
Next article icon

Find Mode in Binary Search tree

Last Updated : 22 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)


Next Article
Inorder successor in Binary Tree

B

bunny09262002
Improve
Article Tags :
  • Hash
  • Binary Search Tree
  • DSA
  • Trees
Practice Tags :
  • Binary Search Tree
  • Hash

Similar Reads

  • Search a node in Binary Tree
    Given a Binary tree and a key. The task is to search and check if the given key exists in the binary tree or not. Examples: Input: Output: TrueInput: Output: False Approach:The idea is to use any of the tree traversals to traverse the tree and while traversing check if the current node matches with
    7 min read
  • Minimum in a Binary Search Tree
    Given the root of a Binary Search Tree. The task is to find the minimum valued element in this given BST. Example: Input: Output: 1Explanation: The minimum element in the given BST is 1. Input: Output: 2Explanation: The minimum element in the given BST is 2 Table of Content [Naive Approach] Using In
    12 min read
  • Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is f
    15+ min read
  • Inorder successor in Binary Tree
    Given a binary tree and a node, the task is to find the inorder successor of this node. Inorder Successor of a node in the binary tree is the next node in the Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal. In the below diagram, inorder success
    15 min read
  • Inorder predecessor in Binary Search Tree
    Given a Binary Search Tree, the task is to find the In-Order predecessor of a given target key. In a Binary Search Tree (BST), the Inorder predecessor of a node is the previous node in the Inorder traversal of the BST. The Inorder predecessor is NULL for the first node in the Inorder traversal. Exam
    10 min read
  • Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
  • Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node
    10 min read
  • Optimal Binary Search Tree
    Given a sorted array key [0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches for keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible. The cost of a BST node is the level
    15+ min read
  • Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
  • Binary Search Tree
    A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences