题目描述
题目链接
https://leetcode.com/problems/find-mode-in-binary-search-tree/
方法思路
Approach1: based on HashMap
class Solution {
//Runtime: 6 ms, faster than 51.99%
//Memory Usage: 40.3 MB, less than 54.73%
Map<Integer, Integer> map = new HashMap<>();
public int[] findMode(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root);
int maxVal = -1;
for (int count : map.values()){
if (count > maxVal)
maxVal = count;
}
for (Map.Entry<Integer,Integer> e : map.entrySet()){
if (e.getValue() == maxVal)
res.add(e.getKey());
}
int[] ans = new int[res.size()];
for (int i=0; i<res.size(); i++)
ans[i] = res.get(i);
return ans;
}
private void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
map.put(root.val, map.getOrDefault(root.val, 0) + 1);
dfs(root.right);
}
}
Approach2: without HashMap
public class Solution {
//Runtime: 1 ms, faster than 99.59%
//Memory Usage: 39.2 MB, less than 74.32%
Integer prev = null;
int count = 1;
int max = 0;
public int[] findMode(TreeNode root) {
if (root == null) return new int[0];
List<Integer> list = new ArrayList<>();
traverse(root, list);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); ++i) res[i] = list.get(i);
return res;
}
private void traverse(TreeNode root, List<Integer> list) {
if (root == null) return;
traverse(root.left, list);
if (prev != null) {
if (root.val == prev)
count++;
else
count = 1;
}
if (count > max) {
max = count;
list.clear();
list.add(root.val);
} else if (count == max) {
list.add(root.val);
}
prev = root.val;
traverse(root.right, list);
}
}