# LeetCode算法题-Find Mode in Binary Search Tree（Java实现）

### 01 看题和准备

   1
\
2
/
2


### 02 第一种解法

private Map<Integer, Integer> map;
private int max = 0;
public int[] findMode(TreeNode root) {
if (root == null) {
return new int[0];
}
map = new HashMap<Integer, Integer>();
findMax(root);
List<Integer> list = new LinkedList<>();
for (int key: map.keySet()) {
if (map.get(key) == max) {
}
}
int[] result = new int[list.size()];
for (int i = 0; i<result.length; i++) {
result[i] = list.get(i);
}
return result;
}

public void findMax(TreeNode root) {
if (root.left != null) {
findMax(root.left);
}
map.put(root.val, map.getOrDefault(root.val, 0)+1);
max = Math.max(max, map.get(root.val));
if (root.right != null) {
findMax(root.right);
}
}


### 03 第二种解法

public int[] findMode2(TreeNode root) {
if (root == null) {
return new int[0];
}
int max = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.left != null) {
stack.push(node.left);
}
map.put(node.val, map.getOrDefault(node.val, 0)+1);
max = Math.max(max, map.get(node.val));
if (node.right != null) {
stack.push(node.right);
}
}
List<Integer> list = new LinkedList<>();
for (int key: map.keySet()) {
if (map.get(key) == max) {
}
}
int[] result = new int[list.size()];
for (int i = 0; i<result.length; i++) {
result[i] = list.get(i);
}
return result;
}


### 04 第三种解法

     9
/ \
5   10
/ \  / \
4   8 9  11


Integer prev = null;
int count = 1;
int max2 = 0;
public int[] findMode3(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 > max2) {
max2 = count;
list.clear();
} else if (count == max2) {
}
prev = root.val;
traverse(root.right, list);
}


### 05 小结

02-06 803
06-16 47
10-31 61
01-22 227
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客