Finding Mode in a Binary Search Tree in JavaScript


Mode:

Mode of a set of data is simply the number that occurs for most number of times in that set of data. For instance, 3 is the mode of dataset 2, 3, 1, 3, 4, 2, 3, 1 as it occurs for most number of times.

Binary Search Tree

A tree DS is a valid Binary Search Tree if it fulfils the following conditions −

  • 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.

Problem

We are required to write a JavaScript function that takes in a BST root as the only argument. The BST may or most probably contain duplicates. We are required to find and return the mode of the data stored by the tree.

Example

The code for this will be −

 Live Demo

class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
class BinarySearchTree{
   constructor(){
      // root of a binary seach tree
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(3);
BST.insert(2);
BST.insert(3);
BST.insert(2);
const findMode = function(root) {
   let max = 1;
   const hash = {};
   const result = [];
   const traverse = node => {
      if (hash[node.data]) {
         hash[node.data] += 1;
         max = Math.max(max, hash[node.data]);
      } else {
         hash[node.data] = 1;
      };
      node.left && traverse(node.left);
      node.right && traverse(node.right);
   };
   if(root){
      traverse(root);
   };
   for(const key in hash) {
      hash[key] === max && result.push(key);
   };
   return +result[0];
};
console.log(findMode(BST.root));

Output

And the output in the console will be −

3

Updated on: 04-Mar-2021

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements