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
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Count the number of Nodes in a Binary Tree in Constant Space
Next article icon

Find maximum count of duplicate nodes in a Binary Search Tree

Last Updated : 16 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Search Tree (BST) with duplicates, find the node (the most frequently occurred element) in the given BST. If the BST contains two or more such nodes, print any of them. 
Note: We cannot use any extra space. (Assume that the implicit stack space incurred due to recursion does not count) 
Assume a BST is defined as follows: 
 

  • The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
  • Both the left and right subtrees must also be binary search trees.


Examples: 
 

Input :   Given BST is                      6                  /    \                 5       7               /   \    /  \              4     5  7    7 Output : 7   Input :  Given BST is                       10                  /    \                 5       12               /   \    /  \              5     6  12    16 Output : 5 or 12  We can print any of the two value 5 or 12.


 


Approach:
To find the node, we need to find the Inorder Traversal of the BST because its Inorder Traversal will be in sorted order. 
So, the idea is to do recursive Inorder traversal and keeping the track of the previous node. If the current node value is equal to the previous value we can increase the current count and if the current count becomes greater than the maximum count, replace the element.
Below is the implementation of the above approach: 
 

C++

/* C++ program to find the median of BST in O(n)
   time and O(1) space*/
 
#include <iostream>
using namespace std;
 
/* A binary search tree Node has data, pointer
   to left child and a pointer to right child */
 
struct Node {
    int val;
    struct Node *left, *right;
};
 
struct Node* newNode(int data)
{
    struct Node* temp = new Node;
    temp->val = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// cur for storing the current count of the value
// and mx for the maximum count of the element which is denoted by node
 
int cur = 1, mx = 0;
int node;
struct Node* previous = NULL;
 
// Find the inorder traversal of the BST
void inorder(struct Node* root)
{
    // If root is NULL then return
    if (root == NULL) {
        return;
    }
    inorder(root->left);
    if (previous != NULL) {
        // If the previous value is equal to the current value
        // then increase the count
        if (root->val == previous->val) {
            cur++;
        }
        // Else initialize the count by 1
        else {
            cur = 1;
        }
    }
    // If current count is greater than the max count
    // then update the mx value
    if (cur > mx) {
        mx = cur;
        node = root->val;
    }
    // Make the current Node as previous
    previous = root;
    inorder(root->right);
}
 
// Utility function
int findnode(struct Node* root)
{
    inorder(root);
    return node;
}
int main()
{
    /* Let us create following BST
                   6
                 /    \
                5       7
              /   \    /  \
             4     5  7    7
    */
 
    struct Node* root = newNode(6);
    root->left = newNode(5);
    root->right = newNode(7);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(7);
    root->right->right = newNode(7);
 
    cout << "Node of BST is " << findnode(root) << '\n';
    return 0;
}
                      
                       

Java

/* Java program to find the median of BST
in O(n) time and O(1) space*/
class GFG
{
     
/* A binary search tree Node has data, pointer
to left child and a pointer to right child */
static class Node
{
    int val;
    Node left, right;
};
 
static Node newNode(int data)
{
    Node temp = new Node();
    temp.val = data;
    temp.left = temp.right = null;
    return temp;
}
 
// cur for storing the current count
// of the value and mx for the maximum count
// of the element which is denoted by node
static int cur = 1, mx = 0;
static int node;
static Node previous = null;
 
// Find the inorder traversal of the BST
static void inorder(Node root)
{
    // If root is null then return
    if (root == null)
    {
        return;
    }
    inorder(root.left);
    if (previous != null)
    {
         
        // If the previous value is equal to
        // the current value then increase the count
        if (root.val == previous.val)
        {
            cur++;
        }
         
        // Else initialize the count by 1
        else
        {
            cur = 1;
        }
    }
     
    // If current count is greater than the
    // max count then update the mx value
    if (cur > mx)
    {
        mx = cur;
        node = root.val;
    }
     
    // Make the current Node as previous
    previous = root;
    inorder(root.right);
}
 
// Utility function
static int findnode(Node root)
{
    inorder(root);
    return node;
}
 
// Java Code
public static void main(String args[])
{
    /* Let us create following BST
                6
                / \
                5     7
            / \ / \
            4     5 7 7
    */
    Node root = newNode(6);
    root.left = newNode(5);
    root.right = newNode(7);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.left = newNode(7);
    root.right.right = newNode(7);
 
    System.out.println("Node of BST is " +
                          findnode(root));
}
}
 
// This code is contributed by Arnab Kundu
                      
                       

Python3

# Python program to find the median of BST
# in O(n) time and O(1) space
 
# A binary search tree Node has data, pointer
# to left child and a pointer to right child
class Node:
    def __init__(self):
        self.val = 0
        self.left = None
        self.right = None
 
def newNode(data: int) -> Node:
    temp = Node()
    temp.val = data
    temp.left = temp.right = None
    return temp
 
# cur for storing the current count
# of the value and mx for the maximum count
# of the element which is denoted by node
cur = 1
mx = 0
node = 0
previous = Node()
 
# Find the inorder traversal of the BST
def inorder(root: Node):
    global cur, mx, node, previous
 
    # If root is null then return
    if root is None:
        return
 
    inorder(root.left)
 
    if previous is not None:
 
        # If the previous value is equal to
        # the current value then increase the count
        if root.val == previous.val:
            cur += 1
 
        # Else initialize the count by 1
        else:
            cur = 1
 
    # If current count is greater than the
    # max count then update the mx value
    if cur > mx:
        mx = cur
        node = root.val
 
    # Make the current Node as previous
    previous = root
    inorder(root.right)
 
# Utility function
def findNode(root: Node) -> int:
    global node
 
    inorder(root)
    return node
 
# Driver Code
if __name__ == "__main__":
    # Let us create following BST
    #         6
    #         / \
    #     5     7
    #     / \ / \
    #     4 5 7 7
    root = newNode(6)
    root.left = newNode(5)
    root.right = newNode(7)
    root.left.left = newNode(4)
    root.left.right = newNode(5)
    root.right.left = newNode(7)
    root.right.right = newNode(7)
 
    print("Node of BST is", findNode(root))
 
# This code is contributed by
# sanjeev2552
                      
                       

C#

/* C# program to find the median of BST
in O(n) time and O(1) space*/
using System;
     
class GFG
{
     
/* A binary search tree Node has data, pointer
to left child and a pointer to right child */
public class Node
{
    public int val;
    public Node left, right;
};
 
static Node newNode(int data)
{
    Node temp = new Node();
    temp.val = data;
    temp.left = temp.right = null;
    return temp;
}
 
// cur for storing the current count
// of the value and mx for the maximum count
// of the element which is denoted by node
static int cur = 1, mx = 0;
static int node;
static Node previous = null;
 
// Find the inorder traversal of the BST
static void inorder(Node root)
{
    // If root is null then return
    if (root == null)
    {
        return;
    }
    inorder(root.left);
    if (previous != null)
    {
         
        // If the previous value is equal to
        // the current value then increase the count
        if (root.val == previous.val)
        {
            cur++;
        }
         
        // Else initialize the count by 1
        else
        {
            cur = 1;
        }
    }
     
    // If current count is greater than the
    // max count then update the mx value
    if (cur > mx)
    {
        mx = cur;
        node = root.val;
    }
     
    // Make the current Node as previous
    previous = root;
    inorder(root.right);
}
 
// Utility function
static int findnode(Node root)
{
    inorder(root);
    return node;
}
 
// Driver Code
public static void Main(String []args)
{
    /* Let us create following BST
                6
                / \
                5     7
            / \ / \
            4     5 7 7
    */
    Node root = newNode(6);
    root.left = newNode(5);
    root.right = newNode(7);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.left = newNode(7);
    root.right.right = newNode(7);
 
    Console.WriteLine("Node of BST is " +
                         findnode(root));
}
}
 
// This code is contributed by PrinciRaj1992
                      
                       

Javascript

<script>
 
/* Javascript program to find the median of BST
in O(n) time and O(1) space*/
     
/* A binary search tree Node has data, pointer
to left child and a pointer to right child */
class Node
{
    constructor()
    {
        this.val = 0;
        this.left = null;
        this.right = null;
    }
};
 
function newNode(data)
{
    var temp = new Node();
    temp.val = data;
    temp.left = temp.right = null;
    return temp;
}
 
// cur for storing the current count
// of the value and mx for the maximum count
// of the element which is denoted by node
var cur = 1, mx = 0;
var node;
var previous = null;
 
// Find the inorder traversal of the BST
function inorder(root)
{
    // If root is null then return
    if (root == null)
    {
        return;
    }
    inorder(root.left);
    if (previous != null)
    {
         
        // If the previous value is equal to
        // the current value then increase the count
        if (root.val == previous.val)
        {
            cur++;
        }
         
        // Else initialize the count by 1
        else
        {
            cur = 1;
        }
    }
     
    // If current count is greater than the
    // max count then update the mx value
    if (cur > mx)
    {
        mx = cur;
        node = root.val;
    }
     
    // Make the current Node as previous
    previous = root;
    inorder(root.right);
}
 
// Utility function
function findnode(root)
{
    inorder(root);
    return node;
}
 
// Driver Code
/* Let us create following BST
            6
            / \
            5     7
        / \ / \
        4     5 7 7
*/
var root = newNode(6);
root.left = newNode(5);
root.right = newNode(7);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(7);
root.right.right = newNode(7);
document.write("Node of BST is " +
                     findnode(root));
 
// This code is contributed by noob2000.
</script>
                      
                       

Output: 
node of BST is 7

 

Time complexity : O(N)
Auxiliary Space: O(N).  
 



Next Article
Count the number of Nodes in a Binary Tree in Constant Space
author
ojas_bansal
Improve
Article Tags :
  • Binary Search Tree
  • Data Structures
  • DSA
Practice Tags :
  • Binary Search Tree
  • Data Structures

Similar Reads

  • Count of duplicate Subtrees in an N-ary Tree
    Given the root of an n-ary tree, the task is to find the number of subtrees that have duplicates in the n-ary tree. Two trees are duplicates if they have the same structure with the same node values. Examples: Input: 1 N 2 2 3 N 4 N 4 4 3 N N N N NOutput: 2Explanation: [4], [3] are duplicate subtree
    6 min read
  • Find all duplicate levels of given Binary Tree
    A binary tree is a tree data structure in which each node has at most two child nodes, referred to as the left and right children. In this question, the task is to find all the duplicate levels of a given binary tree. This problem can be used to identify and resolve any duplicate nodes or values in
    13 min read
  • Count the number of Nodes in a Binary Tree in Constant Space
    Given a binary tree having N nodes, count the number of nodes using constant O(1) space. This can be done by simple traversals like- Preorder, InOrder, PostOrder, and LevelOrder but these traversals require an extra space which is equal to the height of the tree. Examples: Input: Output: 5Explanatio
    10 min read
  • Find Mode in Binary Search tree
    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 50Explanation: 50 is repeated 2 times, and all other nodes occur only
    10 min read
  • How to handle duplicates in Binary Search Tree?
    In a Binary Search Tree (BST), all keys in the left subtree of a key must be smaller and all keys in the right subtree must be greater. So a Binary Search Tree by definition has distinct keys. How can duplicates be allowed where every insertion inserts one more key with a value and every deletion de
    15+ min read
  • Count Non-Leaf nodes in a Binary Tree
    Given a Binary tree, count the total number of non-leaf nodes in the tree Examples: Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
    10 min read
  • Count paths in a Binary Tree consisting of nodes in non-decreasing order
    Given a Binary Tree consisting of N nodes, the task is to find the number of paths from the root to any node X, such that all the node values in that path are at most X. Examples: Input: Below is the given Tree: Output: 4Explanation: The paths from the root to any node X that have value at most valu
    15 min read
  • Count of nodes in a binary tree having their nodes in range [L, R]
    Given a Binary Tree consisting of n nodes and two positive integers l and r, the task is to find the count of nodes having their value in the range [l, r]. Examples: Input: l = 4, r = 15 Output: 4Explanation: The nodes in the given Tree that lies in the range [4, 15] are {4, 5, 6, 7}. Input: l = 1,
    10 min read
  • Count of Fibonacci paths in a Binary tree
    Given a Binary Tree, the task is to count the number of Fibonacci paths in the given Binary Tree. Fibonacci Path is a path which contains all nodes in root to leaf path are terms of Fibonacci series. Example: Input: 0 / \ 1 1 / \ / \ 1 10 70 1 / \ 81 2 Output: 2 Explanation: There are 2 Fibonacci pa
    10 min read
  • Sum of cousins of a given node in a Binary Tree
    Given a binary tree and data value of a node. The task is to find the sum of cousin nodes of given node. If given node has no cousins then return -1. Note: It is given that all nodes have distinct values and the given node exists in the tree. Examples: Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 1
    11 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