Appearance
Approach: Traverse counting value frequencies, then return all keys with the maximum count.
Complexity: O(n) time, O(n) space
js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var findMode = function(root) {
const map = {}
traverse(root, map)
const maxCount = Math.max(...Object.values(map))
return Object.keys(map).reduce((ret, key) => {
if (map[key] === maxCount) {
ret.push(parseInt(key))
}
return ret
}, [])
};
function traverse(root, map) {
if (root === null) {
return
}
map[root.val] = (map[root.val] || 0) + 1
traverse(root.left, map)
traverse(root.right, map)
}