leetcode二叉树-501. 二叉搜索树中的众数

网友投稿 225 2022-11-22

leetcode二叉树-501. 二叉搜索树中的众数

考点:遍历,然后转化成数组中找众数

package binarytree.findMode;import binarytree.untils.GenerateTreeNode;import binarytree.untils.TreeNode;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * 501. 二叉搜索树中的众数 * 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 * * 假定 BST 有如下定义: * * 结点左子树中所含结点的值小于等于当前结点的值 * 结点右子树中所含结点的值大于等于当前结点的值 * 左子树和右子树都是二叉搜索树 * 例如: * 给定 BST [1,null,2,2], * * 1 * \ * 2 * / * 2 * 返回[2]. * * 提示:如果众数超过1个,不需考虑输出顺序 */public class findMode { /** * 搜索遍历 * @param root * @return */ public static int[] findMode(TreeNode root) { Map map = new HashMap<>(); inOrder(root,map); int max = 0; for (Map.Entry m: map.entrySet()) { max=Math.max(max,m.getValue()); } List res1 = new ArrayList<>(); int i = 0; for (Map.Entry m: map.entrySet()) { if(m.getValue()==max){ res1.add(m.getKey()); } } int[] res = new int[res1.size()]; for (int j = 0; j < res1.size(); j++) { res[j] = res1.get(j); } return res; } private static void inOrder(TreeNode root,Map map){ if(root == null){ return; } if(map.containsKey(root.val)){ int count = map.get(root.val); map.put(root.val,++count); } else{ map.put(root.val,1); } inOrder(root.left,map); inOrder(root.right,map); } public static void main(String[] args) { Integer[] nums = {1,null,2}; TreeNode treeNode = GenerateTreeNode.generateTreeNode(nums); int[] mode = findMode(treeNode); for (int i = 0; i < mode.length; i++) { System.out.println(mode[i]); } }}

不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Patton交付带ADSL接口的SmartNode VoIP IAD
下一篇:springboot ApplicationContextInitializer的三种使用方法小结
相关文章

 发表评论

暂时没有评论,来抢沙发吧~