KatInterview

501. Find Mode in Binary Search Tree

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the mode(s) — the most frequently occurring element(s) — in a Binary Search Tree (BST) that may contain duplicates. The BST is defined such that for any node, values in its left subtree are less than or equal to its own value, and values in its right subtree are greater than or equal to its own value (left.val <= node.val <= right.val).

Solution

Find Mode in Binary Search Tree in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        # Initialize state variables as instance attributes
        self.modes = []
        self.max_freq = 0
        self.current_freq = 0
        # Using None for prev_val handles the first node case gracefully
        self.prev_val = None

        self.inorder(root)

        return self.modes

    def inorder(self, node: Optional[TreeNode]):
        if not node:
            return
        
        # Traverse the left subtree first
        self.inorder(node.left)

        # Process the current node
        if self.prev_val is not None and self.prev_val == node.val:
            # If the current node's value is the same as the previous one, increment frequency.
            self.current_freq += 1
        else:
            # Otherwise, it's a new number, reset frequency to 1.
            self.current_freq = 1

        if self.current_freq > self.max_freq:
            # If we found a new most frequent number
            self.max_freq = self.current_freq
            self.modes = [node.val] # Clear previous modes
        elif self.current_freq == self.max_freq:
            # If we found another number with the same max frequency
            self.modes.append(node.val)

        # Update prev_val before moving to the right subtree
        self.prev_val = node.val

        # Traverse the right subtree
        self.inorder(node.right)

Find Mode in Binary Search Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private List<Integer> modes;
    private int maxFreq;
    private int currentFreq;
    // Using the Integer wrapper class allows `prevVal` to be null,
    // which gracefully handles the first node in the traversal.
    private Integer prevVal;

    public int[] findMode(TreeNode root) {
        modes = new ArrayList<>();
        maxFreq = 0;
        currentFreq = 0;
        prevVal = null;

        inorder(root);

        // Convert the list of modes to an int array for the final result.
        int[] result = new int[modes.size()];
        for (int i = 0; i < modes.size(); i++) {
            result[i] = modes.get(i);
        }
        return result;
    }

    private void inorder(TreeNode node) {
        if (node == null) {
            return;
        }

        // Traverse the left subtree first
        inorder(node.left);

        // Process the current node
        if (prevVal != null && prevVal == node.val) {
            // If the current node's value is the same as the previous one, increment frequency.
            currentFreq++;
        } else {
            // Otherwise, it's a new number, reset frequency to 1.
            currentFreq = 1;
        }

        if (currentFreq > maxFreq) {
            // If we found a new most frequent number
            maxFreq = currentFreq;
            modes.clear(); // Clear previous modes
            modes.add(node.val);
        } else if (currentFreq == maxFreq) {
            // If we found another number with the same max frequency
            modes.add(node.val);
        }

        // Update prevVal before moving to the right subtree
        prevVal = node.val;

        // Traverse the right subtree
        inorder(node.right);
    }
}

Find Mode in Binary Search Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    vector<int> modes;
    int maxFreq = 0;
    int currentFreq = 0;
    // Using a pointer for `prev` allows us to easily handle the first node case,
    // where `prev` is `nullptr`.
    TreeNode* prev = nullptr;

    void inorder(TreeNode* node) {
        if (!node) {
            return;
        }

        // Traverse the left subtree first
        inorder(node->left);

        // Process the current node
        if (prev != nullptr && prev->val == node->val) {
            // If the current node's value is the same as the previous one, increment frequency.
            currentFreq++;
        } else {
            // Otherwise, it's a new number, reset frequency to 1.
            currentFreq = 1;
        }

        if (currentFreq > maxFreq) {
            // If we found a new most frequent number
            maxFreq = currentFreq;
            modes.clear(); // Clear previous modes
            modes.push_back(node->val);
        } else if (currentFreq == maxFreq) {
            // If we found another number with the same max frequency
            modes.push_back(node->val);
        }

        // Update prev to the current node before moving to the right subtree
        prev = node;

        // Traverse the right subtree
        inorder(node->right);
    }

public:
    vector<int> findMode(TreeNode* root) {
        // The class members will be updated by the inorder traversal.
        inorder(root);
        return modes;
    }
};

Find Mode in Binary Search Tree in TypeScript

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

function findMode(root: TreeNode | null): number[] {
    let modes: number[] = [];
    let maxFreq = 0;
    let currentFreq = 0;
    // Using null for prevVal handles the first node case gracefully
    let prevVal: number | null = null;

    function inorder(node: TreeNode | null) {
        if (node === null) {
            return;
        }

        // Traverse the left subtree first
        inorder(node.left);

        // Process the current node
        if (prevVal !== null && prevVal === node.val) {
            // If the current node's value is the same as the previous one, increment frequency.
            currentFreq++;
        } else {
            // Otherwise, it's a new number, reset frequency to 1.
            currentFreq = 1;
        }

        if (currentFreq > maxFreq) {
            // If we found a new most frequent number
            maxFreq = currentFreq;
            modes = [node.val]; // Clear previous modes
        } else if (currentFreq === maxFreq) {
            // If we found another number with the same max frequency
            modes.push(node.val);
        }

        // Update prevVal before moving to the right subtree
        prevVal = node.val;

        // Traverse the right subtree
        inorder(node.right);
    }

    inorder(root);
    return modes;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.