BFS Solution with Runtime Complexity O(n) -> O(n log n)
(TreeNode root)
| 3 | * BFS Solution with Runtime Complexity O(n) -> O(n log n) |
| 4 | */ |
| 5 | public int[] findMode(TreeNode root) { |
| 6 | if (root == null) return new int[0]; |
| 7 | List<Integer> curr = new ArrayList<>(); |
| 8 | Map<Integer, Integer> freqMap = new HashMap<>(); |
| 9 | Queue<TreeNode> q = new ArrayDeque<>(); |
| 10 | q.offer(root); |
| 11 | |
| 12 | while (!q.isEmpty()) { |
| 13 | int n = q.size(); |
| 14 | for (int i = 0; i < n; i++) { |
| 15 | TreeNode node = q.poll(); |
| 16 | if (freqMap.containsKey(node.val)) |
| 17 | freqMap.put(node.val, freqMap.get(node.val) + 1); |
| 18 | else |
| 19 | freqMap.put(node.val, 1); |
| 20 | |
| 21 | if (node.left != null) q.offer(node.left); |
| 22 | if (node.right != null) q.offer(node.right); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | int currMax = 0; |
| 27 | for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) { |
| 28 | int key = entry.getKey(); |
| 29 | int value = entry.getValue(); |
| 30 | |
| 31 | if (value > currMax) { |
| 32 | curr.clear(); |
| 33 | curr.add(key); |
| 34 | currMax = Math.max(currMax, value); |
| 35 | } else if (value == currMax){ |
| 36 | curr.add(key); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | int[] res = new int[curr.size()]; |
| 41 | for (int j = 0; j < curr.size(); j++) { |
| 42 | res[j] = curr.get(j); |
| 43 | } |
| 44 | return res; |
| 45 | } |
| 46 | } |