package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * https://leetcode.com/problems/find-mode-in-binary-search-tree/
 */
public class Problem501 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    private static class IntRef {
        int val;
    }

    public int[] findMode(TreeNode root) {
        Map<Integer, Integer> map = new HashMap<>();
        IntRef max = new IntRef();
        findMode(root, map, max);
        List<Integer> list = new ArrayList<>();
        map.forEach((val, count) -> {
            if (count == max.val) {
                list.add(val);
            }
        });
        int[] result = new int[list.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = list.get(i);
        }
        return result;
    }

    private void findMode(TreeNode node, Map<Integer, Integer> map, IntRef max) {
        if (node == null) {
            return;
        }
        if (!map.containsKey(node.val)) {
            if (max.val < 1) {
                max.val = 1;
            }
            map.put(node.val, 1);
        } else {
            int newCount = map.get(node.val) + 1;
            if (max.val < newCount) {
                max.val = newCount;
            }
            map.put(node.val, newCount);
        }
        findMode(node.left, map, max);
        findMode(node.right, map, max);
    }

    public static void main(String[] args) {
        Problem501 prob = new Problem501();

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(2);

        System.out.println(Arrays.toString(prob.findMode(root))); // [1,2]
    }
}

@@ -44,33 +44,8 @@
 st;%0A
-import java.util.Arrays;%0A
 impo
@@ -1534,339 +1534,7 @@
    %7D
-%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem501 prob = new Problem501();%0A%0A        TreeNode root = new TreeNode(1);%0A        root.left = new TreeNode(1);%0A        root.right = new TreeNode(2);%0A        root.right.left = new TreeNode(2);%0A%0A        System.out.println(Arrays.toString(prob.findMode(root))); // %5B1,2%5D%0A    %7D
 %0A%7D%0A

Solve problem 501