二叉搜索树中的众数
题目
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
1
2
/
2
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
- 笨办法,使用递归,递归终结的条件是当前节点为null,先考虑使用额外空间,则需要一个map来存储每个数字出现的次数,然后再找到最大的次数,再遍历查找到众数
代码
- 领扣中另一个思路是递归中进行比较,递归完成后即可返回
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] findMode(TreeNode root) {
//使用递归,递归终结的条件是当前节点为null,先考虑使用额外空间,则需要一个map来存储每个数字出现的次数,然后再找到最大的次数,再遍历查找到众数.
Map<Integer,Integer> map = new HashMap();
recursion(root,map);
int max = 0;
for(Integer key:map.keySet()){
if(max < map.get(key)){
max = map.get(key);
}
}
ArrayList<Integer> result = new ArrayList<>();
for(Integer key:map.keySet()){
if(map.get(key) == max){
result.add(key);
}
}
int[] temp = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
temp[i] = result.get(i);
}
return temp;
}
public void recursion(TreeNode root,Map<Integer,Integer> map){
if(root == null){
return;
}
map.put(root.val,map.getOrDefault(root.val,0)+1);
recursion(root.left,map);
recursion(root.right,map);
}
}
- 第二种
int maxTimes = 0;
int thisTimes = 0;
List<Integer> res = new LinkedList<Integer>();
TreeNode pre = null;
public int[] findMode(TreeNode root) {
inOrder(root);
int length = res.size();
int[] rr = new int[length];
for(int i = 0; i < length; i++) {
rr[i] = res.get(i);
}
return rr;
}
public void inOrder(TreeNode root) {
if(root == null) {
return;
}
inOrder(root.left);
if(pre != null && pre.val == root.val) {
thisTimes++;
} else {
thisTimes = 1;
}
if(thisTimes == maxTimes) {
res.add(root.val);
} else if(thisTimes > maxTimes) {
maxTimes = thisTimes;
res.clear();
res.add(root.val);
}
pre = root;
inOrder(root.right);
}
作者:nuan
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/solution/zhong-xu-bian-li-listcun-zhong-shu-by-nuan/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。