Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
class Solution {
private Map<Integer, Integer> hashMap = new HashMap<>();
private int max = 1;
public int[] findMode(TreeNode root) {
if(root == null){
return new int[0];
}
helper(root);
int result[] = new int[hashMap.size()]; int i = 0;
for(Integer k: hashMap.keySet()){
if(hashMap.get(k) == max)
result[i++] = k;
}
return Arrays.copyOf(result, i);
}
private void helper(TreeNode root){
if(root != null){
if(hashMap.containsKey(root.val)){
int count = hashMap.get(root.val) + 1;
hashMap.put(root.val, hashMap.get(root.val) + 1);
max = Math.max(max, count);
}
else
hashMap.put(root.val, 1);
helper(root.left);
helper(root.right);
}
}
}