File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments