Find Mode in Binary Search Tree LeetCode solution in JavaScript

1
/**
2
* Definition for a binary tree node.
3
* function TreeNode(val, left, right) {
4
* this.val = (val===undefined ? 0 : val)
5
* this.left = (left===undefined ? null : left)
6
* this.right = (right===undefined ? null : right)
7
* }
8
*/
9
/**
10
* @param {TreeNode} root
11
* @return {number[]}
12
*/
13
var findMode = function (root) {
14
const dup = new Map();
15

16
helper(root, dup);
17

18
let res = [];
19
let max = Number.MIN_VALUE;
20
for (const [key, value] of dup) {
21
if (value > 1 && value >= max) {
22
res.push(key);
23
max = Math.max(max, value);
24
}
25
}
26

27
return res.length > 0 ? res : [...dup.keys()];
28
};
29

30
function helper(root, dup) {
31
if (root !== null) {
32
dup.set(root.val, ~~dup.get(root.val) + 1);
33
helper(root.left, dup);
34
helper(root.right, dup);
35
}
36
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0