1
+
2
+ namespace LeetCodeSolutions . BinaryTreeBfs ;
3
+
4
+ public class AverageLevelsOfBinaryTree
5
+ {
6
+ public IList < double > AverageOfLevels ( TreeNode root ) {
7
+
8
+ Dictionary < int , Tuple < int , long > > map = new Dictionary < int , Tuple < int , long > > ( ) ;
9
+ _dfs ( root , 0 , map ) ;
10
+
11
+ IList < double > result = new List < double > ( ) ;
12
+ foreach ( var kvp in map )
13
+ {
14
+ result . Add ( ( double ) kvp . Value . Item2 / kvp . Value . Item1 ) ;
15
+ }
16
+
17
+ return result ;
18
+ }
19
+
20
+ private void _dfs ( TreeNode node , int depth , Dictionary < int , Tuple < int , long > > map )
21
+ {
22
+ if ( node != null )
23
+ {
24
+ if ( map . ContainsKey ( depth ) )
25
+ {
26
+ var currentVal = map [ depth ] ;
27
+ map [ depth ] = Tuple . Create ( currentVal . Item1 + 1 , currentVal . Item2 + node . val ) ;
28
+ }
29
+ else
30
+ {
31
+ map [ depth ] = Tuple . Create ( 1 , ( long ) node . val ) ;
32
+ }
33
+ _dfs ( node . left , depth + 1 , map ) ;
34
+ _dfs ( node . right , depth + 1 , map ) ;
35
+ }
36
+ }
37
+
38
+ [ Test ( Description = "https://leetcode.com/problems/average-of-levels-in-binary-tree" ) ]
39
+ [ Category ( "Easy" ) ]
40
+ [ Category ( "LeetCode" ) ]
41
+ [ Category ( "Average Of Levels in Binary Tree" ) ]
42
+ [ TestCaseSource ( nameof ( Input ) ) ]
43
+ [ Category ( "Binary Tree BFS" ) ]
44
+ [ Category ( "TopInterview" ) ]
45
+ public void Test1 ( ( IList < double > Output , int ? [ ] Input ) item )
46
+ {
47
+ var response = AverageOfLevels ( item . Input . ToTreeNode ( ) ) ;
48
+ Assert . That ( response , Is . EqualTo ( item . Output ) ) ;
49
+ }
50
+
51
+ public static IEnumerable < ( IList < double > Output , int ? [ ] Input ) > Input =>
52
+ new List < ( IList < double > Output , int ? [ ] Input ) > ( )
53
+ {
54
+ ( [ 3.00000 , 14.50000 , 11.00000 ] , [ 3 , 9 , 20 , null , null , 15 , 7 ] ) ,
55
+ ( [ 2147483647.00000 , 2147483647.00000 ] , [ 2147483647 , 2147483647 , 2147483647 ] ) ,
56
+ } ;
57
+ }
0 commit comments