Formatted question description: https://leetcode.ca/all/501.html

501. Find Mode in Binary Search Tree

Level

Easy

Description

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

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

For example:

Given BST [1,null,2,2],

   1
    \
     2
    /
   2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

Solution

First do breadth first search on the binary tree to find each value’s number of occurrences. Then find the maximum number of occurrences and the numbers that have the maximum number of occurrences.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] findMode(TreeNode root) {
        if (root == null)
            return new int[0];
        Map<Integer, Integer> countsMap = new HashMap<Integer, Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            int value = node.val;
            int count = countsMap.getOrDefault(value, 0);
            count++;
            countsMap.put(value, count);
            TreeNode left = node.left, right = node.right;
            if (left != null)
                queue.offer(left);
            if (right != null)
                queue.offer(right);
        }
        int maxCount = 0;
        Map<Integer, List<Integer>> countValuesMap = new HashMap<Integer, List<Integer>>();
        Set<Integer> valuesSet = countsMap.keySet();
        for (int value : valuesSet) {
            int count = countsMap.get(value);
            maxCount = Math.max(maxCount, count);
            List<Integer> values = countValuesMap.getOrDefault(count, new ArrayList<Integer>());
            values.add(value);
            countValuesMap.put(count, values);
        }
        List<Integer> maxCountValues = countValuesMap.get(maxCount);
        int length = maxCountValues.size();
        int[] modes = new int[length];
        for (int i = 0; i < length; i++)
            modes[i] = maxCountValues.get(i);
        return modes;
    }
}

All Problems

All Solutions