1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { private final Map<Integer, Integer> map = new HashMap<>();
public int[] findMode(TreeNode root) { dfs(root); int max = Integer.MIN_VALUE; for (int key : map.keySet()) { max = Math.max(max, map.get(key)); } List<Integer> keys = new ArrayList<>(); for (int key : map.keySet()) { if (map.get(key) == max) { keys.add(key); } } int[] ans = new int[keys.size()]; for (int i = 0; i < ans.length; i++) { ans[i] = keys.get(i); } return ans; }
private void dfs(TreeNode root) { if (root == null) { return; } if (map.containsKey(root.val)) { map.put(root.val, map.get(root.val) + 1); } else { map.put(root.val, 1); } dfs(root.left); dfs(root.right); } }
|