Leetcode 501.二叉搜索树中的众数
题目要求
示例 1:

输入:root = [1,null,2,2]
输出:[2]
示例 2:
输入:root = [0]
输出:[0]
双指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
class Solution { private List<Integer> list = new ArrayList<>(); private TreeNode pre = null; private int maxCount = 0; private int count = 0; public int[] findMode(TreeNode root) { traverse(root); return list.stream().mapToInt(i -> i).toArray(); } public void traverse(TreeNode root) { if (root == null) return; traverse(root.left); if(pre!=null){ if (root.val == pre.val) { count++; }else { count = 1; } }else{ count++; } if (count > maxCount) { maxCount = count; list.clear(); list.add(root.val); }else if(count == maxCount){ list.add(root.val); } pre = root; traverse(root.right); } }
|
暴力
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Solution { public int[] findMode(TreeNode root) { Map<Integer, Integer> map = new HashMap<>(); List<Integer> list = new ArrayList<>(); if (root == null) return list.stream().mapToInt(Integer::intValue).toArray(); inorderTraversal(root, map); List<Map.Entry<Integer,Integer>> mapList = map.entrySet().stream() .sorted((s1,s2) -> s2.getValue().compareTo(s1.getValue())) .collect(Collectors.toList()); list.add(mapList.get(0).getKey());
for (int i = 1; i < mapList.size(); i++) { if (mapList.get(i).getValue() == mapList.get(i-1).getValue()) { list.add(mapList.get(i).getKey()); }else { break; } } return list.stream().mapToInt(Integer::intValue).toArray(); }
public void inorderTraversal(TreeNode root, Map<Integer, Integer> map) { if(root == null) return; inorderTraversal(root.left, map); map.put(root.val, map.getOrDefault(root.val, 0) + 1); inorderTraversal(root.right, map); } }
|