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

01 看题和准备

1

\

2

/

2

02 第一种解法

private Map map;

private int max = 0;

public int[] findMode(TreeNode root) {

if (root == null) {

return new int[0];

}

map = new HashMap();

findMax(root);

for (int key: map.keySet()) {

if (map.get(key) == max) {

}

}

int[] result = new int[list.size()];

for (int i = 0; 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 map = new HashMap();

Stack stack = new Stack();

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);

}

}

for (int key: map.keySet()) {

if (map.get(key) == max) {

}

}

int[] result = new int[list.size()];

for (int i = 0; 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 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 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 小结

10-31 61
02-06 803
06-16 47
06-06 4300