Ugly but straight forward Java solution

• First, here is the definition of `Mean, Median, Mode, and Range` http://www.purplemath.com/modules/meanmode.htm

Idea is just traverse through the tree and record (val, count) in a map. After that, find the max count in the map and create return array.

``````public class Solution {
int max = 0;

public int[] findMode(TreeNode root) {
if (root == null) return new int[0];
Map<Integer, Integer> map = new LinkedHashMap<>();
traverse(root, map);

List<Integer> res = new ArrayList<>();
for (int key: map.keySet()) {
if (map.get(key) == max) {
}
}

int[] result = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
result[i] = res.get(i);
}

return result;
}

private void traverse(TreeNode root, Map<Integer, Integer> map) {
if (root == null) return;

Integer value = map.getOrDefault(root.val, 0) + 1;
max = Math.max(max, value);
map.put(root.val, value);

traverse(root.left, map);
traverse(root.right, map);
}
}
``````

• ``````Integer value = map.getOrDefault(root.val, 0) + 1;
``````

what if the root.val is 0, the default value ?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.