Leetcode 501 Find Mode in Binary Search Tree Solution in Java | Hindi Coding Community

0

 


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);
}
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !