-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-501-Find-Mode-in-Binary-Search-Tree.java
87 lines (73 loc) · 2.49 KB
/
LeetCode-501-Find-Mode-in-Binary-Search-Tree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// 1.Using a HashMap + inorder traversal DFS, Space O(N)
// public int[] findMode(TreeNode root) {
// List<Integer> result = new ArrayList<>();
// if (root == null) return new int[0];
// Map<Integer, Integer> map = new HashMap<>();
// int[] max = new int[] {0};
// inorderTraversal(root, map, max);
// for (int key : map.keySet()) {
// if (map.get(key) == max[0]) {
// result.add(key);
// }
// }
// // return result.stream().mapToInt(i -> i).toArray();
// int[] arr = new int[result.size()];
// for (int i = 0; i < result.size(); i++) {
// arr[i] = result.get(i);
// }
// return arr;
// }
// private void inorderTraversal(TreeNode root, Map<Integer, Integer> map, int[] max) {
// if (root == null) return;
// inorderTraversal(root.left, map, max);
// map.put(root.val, map.getOrDefault(root.val, 0) + 1);
// max[0] = Math.max(max[0], map.get(root.val));
// inorderTraversal(root.right, map, max);
// }
// 2.Using variables, two pass solution, Space O(1)
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<>();
inorder(root, list);
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
private void inorder(TreeNode root, List<Integer> list) {
if (root == null) return;
inorder(root.left, list);
if (prev != null) {
// prev is not null, means root is not the first one in inorder traversal array
// prev is null, means root is the first one
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;
inorder(root.right, list);
}
}