Finding Mode in a Binary Search Tree in JavaScript

Mode of a set of data is the number that occurs most frequently. For instance, 3 is the mode of dataset [2, 3, 1, 3, 4, 2, 3, 1] as it appears three times, more than any other number.

Binary Search Tree

A Binary Search Tree (BST) is a tree data structure where:

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

We need to write a JavaScript function that takes a BST root as input and finds the mode (most frequent value) in the tree. The BST may contain duplicate values.

Implementation

Here's the complete solution with BST class and mode finding algorithm:

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

class BinarySearchTree {
    constructor() {
        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);
            }
        }
    }
}

// Create BST and insert values
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(3);
BST.insert(2);
BST.insert(3);
BST.insert(2);

// Function to find mode in BST
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("Mode of BST:", findMode(BST.root));
Mode of BST: 3

How It Works

The algorithm uses these steps:

  1. Traverse: Visit each node in the BST using recursive traversal
  2. Count: Store frequency of each value in a hash table
  3. Track Maximum: Keep track of the highest frequency encountered
  4. Find Mode: Return the value(s) with maximum frequency

Multiple Modes Example

If multiple values have the same highest frequency, all are considered modes:

const BST2 = new BinarySearchTree();
BST2.insert(1);
BST2.insert(1);
BST2.insert(2);
BST2.insert(2);

const findAllModes = 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;
};

console.log("All modes:", findAllModes(BST2.root));
All modes: [ 1, 2 ]

Time and Space Complexity

  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(n) for the hash table and recursion stack

Conclusion

Finding the mode in a BST involves traversing all nodes and counting frequencies using a hash table. The algorithm efficiently handles duplicates and can return single or multiple modes as needed.

Updated on: 2026-03-15T23:19:00+05:30

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements