Find maximum count of duplicate nodes in a Binary Search Tree

16 Aug, 2021
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++
Java
Python3
C#
Javascript
/* 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 BSTvoid 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 functionint 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 program to find the median of BSTin O(n) time and O(1) space*/class GFG{     /* A binary search tree Node has data, pointerto 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 nodestatic int cur = 1, mx = 0;static int node;static Node previous = null; // Find the inorder traversal of the BSTstatic 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 functionstatic int findnode(Node root){    inorder(root);    return node;} // Java Codepublic 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
# 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 childclass 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 nodecur = 1mx = 0node = 0previous = Node() # Find the inorder traversal of the BSTdef 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 functiondef findNode(root: Node) -> int:    global node     inorder(root)    return node # Driver Codeif __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# program to find the median of BSTin O(n) time and O(1) space*/using System;     class GFG{     /* A binary search tree Node has data, pointerto 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 nodestatic int cur = 1, mx = 0;static int node;static Node previous = null; // Find the inorder traversal of the BSTstatic 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 functionstatic int findnode(Node root){    inorder(root);    return node;} // Driver Codepublic 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
<script> /* Javascript program to find the median of BSTin O(n) time and O(1) space*/     /* A binary search tree Node has data, pointerto 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 nodevar cur = 1, mx = 0;var node;var previous = null; // Find the inorder traversal of the BSTfunction 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 functionfunction 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>
node of BST is 7
 
Time complexity : Auxiliary Space: O(N).   
andrew1234
princiraj1992
sanjeev2552
Akanksha_Rai
sooda367
noob2000
pankajsharmagfg
Binary Search Tree
Data Structures
Data Structures
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Flatten BST to sorted list | Increasing order
Largest BST in a Binary Tree | Set 2
Floor and Ceil from a BST
Find median of BST in O(n) time and O(1) space
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion)