Skip to content

Commit 9df78e5

Browse files
authored
Find Mode in Binary Search Tree.js (codesONLY#70)
1 parent 9a20244 commit 9df78e5

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
var findMode = function(r) {
10+
const map = new Map()
11+
const maxMap = new Map()
12+
let max = -Infinity
13+
14+
function dfs(root){
15+
if(!root) return
16+
map.set(root.val, (map.get(root.val) || 0) + 1)
17+
if(map.get(root.val) >= max){
18+
max = map.get(root.val)
19+
if(!maxMap.get(max)) maxMap.set(max, new Set())
20+
maxMap.get(max).add(root.val)
21+
}
22+
dfs(root.left)
23+
dfs(root.right)
24+
}
25+
26+
dfs(r)
27+
return [...maxMap.get(max)]
28+
};

0 commit comments

Comments
 (0)