Skip to content

Commit b53d481

Browse files
committedJan 21, 2023
Add solution #501
1 parent 157d4ed commit b53d481

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@
163163
491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium|
164164
492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy|
165165
500|[Keyboard Row](./0500-keyboard-row.js)|Easy|
166+
501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy|
166167
506|[Relative Ranks](./0506-relative-ranks.js)|Easy|
167168
509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy|
168169
520|[Detect Capital](./0520-detect-capital.js)|Easy|
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 501. Find Mode in Binary Search Tree
3+
* https://leetcode.com/problems/find-mode-in-binary-search-tree/
4+
* Difficulty: Easy
5+
*
6+
* Given the root of a binary search tree (BST) with duplicates, return all
7+
* the mode(s) (i.e., the most frequently occurred element) in it.
8+
*
9+
* If the tree has more than one mode, return them in any order.
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* function TreeNode(val, left, right) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.left = (left===undefined ? null : left)
17+
* this.right = (right===undefined ? null : right)
18+
* }
19+
*/
20+
/**
21+
* @param {TreeNode} root
22+
* @return {number[]}
23+
*/
24+
var findMode = function(root) {
25+
const map = new Map();
26+
dfs(root);
27+
28+
function dfs(root) {
29+
if (!root) return 0;
30+
map.set(root.val, (map.get(root.val) || 0) + 1);
31+
[root.left, root.right].forEach(dfs);
32+
}
33+
34+
const max = Math.max(...map.values());
35+
return Array.from(map.keys()).filter(key => map.get(key) === max);
36+
};

0 commit comments

Comments
 (0)