-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathfind-mode-in-binary-search-tree.js
71 lines (62 loc) · 1.6 KB
/
find-mode-in-binary-search-tree.js
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
/**
* Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
*
* Assume a BST is defined as follows:
*
* The left subtree of a node contains only nodes with keys less than or equal to the node's key.
* The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
* Both the left and right subtrees must also be binary search trees.
* For example:
* Given BST [1,null,2,2],
* 1
* \
* 2
* /
* 2
* return [2].
*
* Note: If a tree has more than one mode, you can return them in any order.
*
* Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion
* does not count).
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
const findMode = root => {
// handle current count
const handleValue = val => {
if (val !== currVal) {
currVal = val;
currCount = 0;
}
currCount++;
if (currCount > maxCount) {
// found a new mode
maxCount = currCount;
modeCount = 1;
modes[0] = currVal;
} else if (currCount === maxCount) {
// found a mode with same count
modes[modeCount] = currVal;
modeCount++;
}
};
const inorder = node => {
if (!node) {
return;
}
inorder(node.left);
handleValue(node.val);
inorder(node.right);
};
let currVal = null;
let currCount = 0;
let maxCount = 0;
let modeCount = 0;
const modes = [];
inorder(root);
return modes.slice(0, modeCount);
};
export default findMode;