VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-mode-in-binary-search-tree/

⇱ Find Mode in Binary Search tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Mode in Binary Search tree

Last Updated : 22 Mar, 2023

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:


Output
Mode of BST is 50 

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

Comment
Article Tags: