给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)

 

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

class Solution {

    HashMap<Integer,Integer> hashMap=new HashMap();

    //hashMap.get(1);

    //hashMap.put(1,2);

    public int[] findMode(TreeNode root) {

        f(root);

        int max=0;

        int j=0;

       ArrayList<Integer> list=new ArrayList<>();

        Set<Integer> integers = hashMap.keySet();

       for(Integer i:integers){

           int y=hashMap.get(i);

           if(y>max) max=y;

       }

 

        for(Integer i:integers){

            if(hashMap.get(i)==max){

                list.add(i);

            } 

        }

 

         int[] result=new int[list.size()];

         for(int i=0;i<list.size();i++){

             result[i]=list.get(i);

         }

 

    return result;

 

    }

    public void f(TreeNode root){

        if(root!=null){

            f(root.left);

            if(hashMap.get(root.val)==null){

                hashMap.put(root.val,1);

            }else{

            int i=hashMap.get(root.val);

            hashMap.put(root.val,i+1);

            }

            f(root.right);

 

        }

 

    }

}