Created
November 1, 2023 17:19
-
-
Save smatthewenglish/931daecd3e0c61953bdf126a9fbe83df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode() {} | |
* TreeNode(int val) { this.val = val; } | |
* TreeNode(int val, TreeNode left, TreeNode right) { | |
* this.val = val; | |
* this.left = left; | |
* this.right = right; | |
* } | |
* } | |
*/ | |
class Solution { | |
Integer maxFrequency = 0; | |
HashMap<Integer, Integer> modeMap = new HashMap<>(); | |
public int[] findMode(TreeNode root) { | |
Integer key = root.val; | |
Integer countKey = 1; | |
if(modeMap.containsKey(key)) { | |
countKey += modeMap.get(key) + 1; | |
} | |
if(countKey > maxFrequency) { | |
maxFrequency = countKey; | |
} | |
modeMap.put(key, countKey); | |
if(root.left != null) { | |
findMode(root.left); | |
} | |
if (root.right != null) { | |
findMode(root.right); | |
} | |
HashSet<Integer> resultSet = new HashSet<>(); | |
modeMap.forEach((keyMap, countKeyMap) -> { | |
if (countKeyMap.equals(maxFrequency)) { | |
resultSet.add(keyMap); | |
} | |
}); | |
int[] output = resultSet.stream().mapToInt(Integer::intValue).toArray(); | |
return output; | |
} | |
} |
Author
smatthewenglish
commented
Nov 1, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment