有没有网站可以做试卷,深圳在建工程查询,河南免费网站建设哪家好,炒股配资网站建设给你一个含重复值的二叉搜索树#xff08;BST#xff09;的根节点 root #xff0c;找出并返回 BST 中的所有 众数#xff08;即#xff0c;出现频率最高的元素#xff09;。
如果树中有不止一个众数#xff0c;可以按 任意顺序 返回。
假定 BST 满足如下定义#xf…给你一个含重复值的二叉搜索树BST的根节点 root 找出并返回 BST 中的所有 众数即出现频率最高的元素。
如果树中有不止一个众数可以按 任意顺序 返回。
假定 BST 满足如下定义
结点左子树中所含节点的值 小于等于 当前节点的值结点右子树中所含节点的值 大于等于 当前节点的值左子树和右子树都是二叉搜索树
public static int[] findMode(TreeNode root) {int[] result; //记录结果ListInteger listnew ArrayList();MapInteger,Integer mapnew HashMap();inorder(root,map);// 1. 获取 entrySet 并转换为 ListListMap.EntryInteger, Integer mapList new ArrayList(map.entrySet());// 2. 对 List 进行排序(从到到小)mapList.sort((c1, c2) - c2.getValue().compareTo(c1.getValue()));//3. 将频率最高的加入list中list.add(mapList.get(0).getKey());for(int i1;imapList.size();i){if(mapList.get(i-1).getValue()mapList.get(i).getValue()){list.add(mapList.get(i).getKey());}else {break;}}//将list转化为数组resultlist.stream().mapToInt(Integer::intValue).toArray();return result;}public static void inorder(TreeNode root,MapInteger,Integer map){if(rootnull) return;inorder(root.left,map);map.put(root.val,map.getOrDefault(root.val,0)1);inorder(root.right,map);}