Skip to main content

Mode in Binary Search Tree

Given a binary search tree, return its mode (you may assume the answer is unique). If the tree is empty, return -1. Note: the mode is the most frequently occurring value in the tree.

Example(s)

Example 1:

Tree:
2
/ \
1 2
Output: 2

Example 2:

Tree:
7
/ \
4 9
/ \ / \
1 4 8 9
\
9
Output: 9

Solution

JavaScript BST Mode Solution


/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
*     this.val = (val===undefined ? 0 : val)
*     this.left = (left===undefined ? null : left)
*     this.right = (right===undefined ? null : right)
* }
*/

/**
* Find the mode in a BST
* @param {TreeNode} root - Root of the BST
* @return {number} - Mode of the BST or -1 if empty
*/
function findMode(root) {
if (!root) return -1;

let currVal = null;
let currCount = 0;
let maxCount = 0;
let mode = null;

function inorder(node) {
  if (!node) return;
  
  inorder(node.left);
  
  if (node.val === currVal) {
    currCount++;
  } else {
    currVal = node.val;
    currCount = 1;
  }
  
  if (currCount > maxCount) {
    maxCount = currCount;
    mode = node.val;
  }
  
  inorder(node.right);
}

inorder(root);
return mode;
}

// Test case 1: [2,1,2]
const tree1 = new TreeNode(2);
tree1.left = new TreeNode(1);
tree1.right = new TreeNode(2);

// Test case 2: [7,4,9,1,4,8,9,null,null,9]
const tree2 = new TreeNode(7);
tree2.left = new TreeNode(4);
tree2.right = new TreeNode(9);
tree2.left.left = new TreeNode(1);
tree2.left.right = new TreeNode(4);
tree2.right.left = new TreeNode(8);
tree2.right.right = new TreeNode(9);
tree2.right.right.right = new TreeNode(9);

// Test cases
console.log(findMode(tree1)); // 2
console.log(findMode(tree2)); // 9
console.log(findMode(null)); // -1
Output:
Click "Run Code" to execute the code and see the results.

Complexity

  • Time Complexity: O(n) - Where n is the number of nodes in the tree
  • Space Complexity: O(h) - Where h is the height of the tree (recursion stack)

Approach

The solution uses an in-order traversal approach:

  1. In-order traversal processes nodes in ascending order (left → root → right)
  2. Track current value and count as we traverse
  3. Update mode whenever we find a value with higher frequency
  4. Return the mode or -1 if the tree is empty

Key Insights

  • In-order traversal leverages BST property to process nodes in ascending order
  • Single pass through the tree is sufficient to find the mode
  • Space optimization using variables instead of storing all frequencies
  • Edge case handling for empty trees
  • Efficient O(n) time complexity as each node is visited once