Skip to content

Commit d6dd137

Browse files
authored
Create 501-find-mode-in-binary-search-tree.js
1 parent eb1454f commit d6dd137

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number[]}
11+
*/
12+
const findMode = function(root) {
13+
if(root == null) return []
14+
const hash = {}
15+
traverse(root, hash)
16+
const res = Object.entries(hash).sort((a, b) => b[1] - a[1])
17+
const result = [res[0][0]]
18+
for(let i = 1; i < res.length; i++) {
19+
if(res[i][1] === res[0][1]) result.push(res[i][0])
20+
else break
21+
}
22+
return result
23+
};
24+
25+
function traverse(node, hash) {
26+
if(node === null) return
27+
hash[node.val] = Object.prototype.hasOwnProperty.call(hash, node.val) ? hash[node.val] + 1 : 1
28+
traverse(node.left, hash)
29+
traverse(node.right, hash)
30+
}

0 commit comments

Comments
 (0)