-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindModeInBinarySearchTree.java
101 lines (82 loc) · 2.35 KB
/
FindModeInBinarySearchTree.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.leetcode.algorithms.easy.binarysearch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
import com.leetcode.util.TreeNode;
public class FindModeInBinarySearchTree {
public static void main(String...strings) {
// Insert input into TreeNode
Scanner scanner = new Scanner(System.in);
String[] inputArr = InputUtil.inputArr(scanner.next());
TreeNode root = null;
for(String input : inputArr) {
if(!"null".equals(input)) {
root = insert(root, Integer.parseInt(input));
}
}
// Find the duplicate
int[] result = findMode(root);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
scanner.close();
}
static TreeNode insert(TreeNode root, int input) {
if(root == null) {
root = new TreeNode(input);
} else {
if(root.val > input) {
root.left = insert(root.left, input);
} else {
root.right = insert(root.right, input);
}
}
return root;
}
static TreeNode searchTreeNode(TreeNode root, Map<Integer, Integer> map) {
if (map.containsKey(root.val)) {
int val = map.get(root.val) + 1;
map.put(root.val, val);
} else {
map.put(root.val, 1);
}
// Search left
if (root.left != null) {
root.left = searchTreeNode(root.left, map);
}
// Search right
if (root.right != null) {
root.right = searchTreeNode(root.right, map);
}
return root;
}
static int[] findMode(TreeNode root) {
if (root == null) {
return new int[0];
}
Map<Integer, Integer> map = new HashMap<>();
searchTreeNode(root, map);
// Get mode
int mode = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() >= mode) {
mode = entry.getValue();
}
}
// Update list
List<Integer> list = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == mode) {
list.add(entry.getKey());
}
}
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}