-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0501-find-mode-in-binary-search-tree.js
More file actions
62 lines (48 loc) · 1.56 KB
/
0501-find-mode-in-binary-search-tree.js
File metadata and controls
62 lines (48 loc) · 1.56 KB
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
/**
* Find Mode In Binary Search Tree
* Time Complexity: O(N)
* Space Complexity: O(H)
*/
var findMode = function (root) {
let globalMaximumFrequency = 0;
let lastEncounteredValue = NaN;
let currentBlockCount = 0;
const findMaxFrequencyTraversal = (nodeParameter) => {
if (!nodeParameter) {
return;
}
findMaxFrequencyTraversal(nodeParameter.left);
if (nodeParameter.val === lastEncounteredValue) {
currentBlockCount++;
} else {
lastEncounteredValue = nodeParameter.val;
currentBlockCount = 1;
}
if (currentBlockCount > globalMaximumFrequency) {
globalMaximumFrequency = currentBlockCount;
}
findMaxFrequencyTraversal(nodeParameter.right);
};
findMaxFrequencyTraversal(root);
let modesFoundCollection = [];
let currentComparisonValue = NaN;
let currentComparisonCount = 0;
const collectModesTraversal = (nodeArgument) => {
if (!nodeArgument) {
return;
}
collectModesTraversal(nodeArgument.left);
if (nodeArgument.val === currentComparisonValue) {
currentComparisonCount++;
} else {
currentComparisonValue = nodeArgument.val;
currentComparisonCount = 1;
}
if (currentComparisonCount === globalMaximumFrequency) {
modesFoundCollection.push(nodeArgument.val);
}
collectModesTraversal(nodeArgument.right);
};
collectModesTraversal(root);
return modesFoundCollection;
};