File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
Original file line number Diff line number Diff line change 163163491|[ Non-decreasing Subsequences] ( ./0491-non-decreasing-subsequences.js ) |Medium|
164164492|[ Construct the Rectangle] ( ./0492-construct-the-rectangle.js ) |Easy|
165165500|[ Keyboard Row] ( ./0500-keyboard-row.js ) |Easy|
166+ 501|[ Find Mode in Binary Search Tree] ( ./0501-find-mode-in-binary-search-tree.js ) |Easy|
166167506|[ Relative Ranks] ( ./0506-relative-ranks.js ) |Easy|
167168509|[ Fibonacci Number] ( ./0509-fibonacci-number.js ) |Easy|
168169520|[ Detect Capital] ( ./0520-detect-capital.js ) |Easy|
You can’t perform that action at this time.
0 commit comments