File tree 2 files changed +52
-0
lines changed
2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 407
407
504|[ Base 7] ( ./0504-base-7.js ) |Easy|
408
408
506|[ Relative Ranks] ( ./0506-relative-ranks.js ) |Easy|
409
409
507|[ Perfect Number] ( ./0507-perfect-number.js ) |Easy|
410
+ 508|[ Most Frequent Subtree Sum] ( ./0508-most-frequent-subtree-sum.js ) |Medium|
410
411
509|[ Fibonacci Number] ( ./0509-fibonacci-number.js ) |Easy|
411
412
520|[ Detect Capital] ( ./0520-detect-capital.js ) |Easy|
412
413
521|[ Longest Uncommon Subsequence I] ( ./0521-longest-uncommon-subsequence-i.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 508. Most Frequent Subtree Sum
3
+ * https://leetcode.com/problems/most-frequent-subtree-sum/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return
7
+ * all the values with the highest frequency in any order.
8
+ *
9
+ * The subtree sum of a node is defined as the sum of all the node values formed by the subtree
10
+ * rooted at that node (including the node itself).
11
+ */
12
+
13
+ /**
14
+ * Definition for a binary tree node.
15
+ * function TreeNode(val, left, right) {
16
+ * this.val = (val===undefined ? 0 : val)
17
+ * this.left = (left===undefined ? null : left)
18
+ * this.right = (right===undefined ? null : right)
19
+ * }
20
+ */
21
+ /**
22
+ * @param {TreeNode } root
23
+ * @return {number[] }
24
+ */
25
+ var findFrequentTreeSum = function ( root ) {
26
+ if ( ! root ) return [ ] ;
27
+
28
+ const map = new Map ( ) ;
29
+ let result = [ ] ;
30
+ let max = 0 ;
31
+
32
+ traverse ( root ) ;
33
+
34
+ for ( const [ sum , freq ] of map ) {
35
+ if ( freq > max ) {
36
+ max = freq ;
37
+ result = [ sum ] ;
38
+ } else if ( freq === max ) {
39
+ result . push ( sum ) ;
40
+ }
41
+ }
42
+
43
+ return result ;
44
+
45
+ function traverse ( node ) {
46
+ if ( ! node ) return 0 ;
47
+ const sum = node . val + traverse ( node . left ) + traverse ( node . right ) ;
48
+ map . set ( sum , ( map . get ( sum ) || 0 ) + 1 ) ;
49
+ return sum ;
50
+ }
51
+ } ;
You can’t perform that action at this time.
0 commit comments