题目:
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
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.
思路:
写个方法,用map来记录每个数字出现的个数,以及最大值。
然后写个arraylist来保存key,因为可能有俩。
然后再遍历一下存入array
Code:
private Map<Integer,Integer> map =new HashMap<>();
private int max = 0;
public int[] findMode(TreeNode root) {
if(root==null)
return new int[0];
inOrdroot(root);
List<Integer> b = new ArrayList<>();
for(int key:map.keySet()){
if (map.get(key) == max)
b.add(key);
}
int []res = new int[b.size()];
for(int i=0;i<res.length;i++){
res[i] = b.get(i);
}
return res;
}
private void inOrdroot(TreeNode root){
if(root.left!=null)
inOrdroot(root.left);
map.put(root.val,map.getOrDefault(root.val, 0) + 1);
max = Math.max(max,map.get(root.val));
if(root.right!=null)
inOrdroot(root.right);
}