LeetCode 501.二叉搜索树的众数
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
- 结点左子树中所含结点的值小于等于当前结点的值
- 结点右子树中所含结点的值大于等于当前结点的值
- 左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
思路:
如果不是二叉搜索树,遍历整个树,用Map存值和频率,最后排个序即可。
如果是二叉搜索树,中序遍历,遍历后比较相邻节点,然后记录出现次数即可,
代码:
暴力解法;
class Solution { public int[] findMode(FindModeInBinarySearchTree.TreeNode root) { Map<Integer, Integer> map = new HashMap<>(); List<Integer> list = new ArrayList<>(); if (root == null) return list.stream().mapToInt(Integer::intValue).toArray(); // 获得频率 Map searchBST(root, map); List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream() .sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue())) .collect(Collectors.toList()); list.add(mapList.get(0).getKey()); // 把频率最高的加入 list 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(); } void searchBST(FindModeInBinarySearchTree.TreeNode curr, Map<Integer, Integer> map) { if (curr == null) return; map.put(curr.val, map.getOrDefault(curr.val, 0) + 1); searchBST(curr.left, map); searchBST(curr.right, map); } }
中序遍历-不使用额外空间,利用二叉搜索树特性
class Solution { ArrayList<Integer> resList; int maxCount; int count; TreeNode pre; public int[] findMode(TreeNode root) { resList = new ArrayList<>(); maxCount = 0; count = 0; pre = null; findMode1(root); int[] res = new int[resList.size()]; for (int i = 0; i < resList.size(); i++) { res[i] = resList.get(i); } return res; } public void findMode1(TreeNode root) { if (root == null) { return; } findMode1(root.left); int rootValue = root.val; // 计数 if (pre == null || rootValue != pre.val) { count = 1; } else { count++; } // 更新结果以及maxCount if (count > maxCount) { resList.clear(); resList.add(rootValue); maxCount = count; } else if (count == maxCount) { resList.add(rootValue); } pre = root; findMode1(root.right); } }
迭代法:
class Solution { public int[] findMode(TreeNode root) { TreeNode pre = null; Stack<TreeNode> stack = new Stack<>(); List<Integer> result = new ArrayList<>(); int maxCount = 0; int count = 0; TreeNode cur = root; while (cur != null || !stack.isEmpty()) { if (cur != null) { stack.push(cur); cur =cur.left; }else { cur = stack.pop(); // 计数 if (pre == null || cur.val != pre.val) { count = 1; }else { count++; } // 更新结果 if (count > maxCount) { maxCount = count; result.clear(); result.add(cur.val); }else if (count == maxCount) { result.add(cur.val); } pre = cur; cur = cur.right; } } return result.stream().mapToInt(Integer::intValue).toArray(); } }
标签:count,cur,int,Day34,随想录,maxCount,null,root,代码 From: https://www.cnblogs.com/dwj-ngu/p/16943115.html