File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ //https://leetcode.com/problems/average-of-levels-in-binary-tree/
2
+ import java .util .ArrayList ;
3
+ import java .util .LinkedList ;
4
+ import java .util .List ;
5
+ import java .util .Queue ;
6
+
7
+ public class AverageOfLevelsBT {
8
+
9
+ // public class TreeNode {
10
+ // int val;
11
+ // TreeNode left;
12
+ // TreeNode right;
13
+ // TreeNode() {}
14
+ // TreeNode(int val) { this.val = val; }
15
+ // TreeNode(int val, TreeNode left, TreeNode right) {
16
+ // this.val = val;
17
+ // this.left = left;
18
+ // this.right = right;
19
+ // }
20
+ // }
21
+
22
+ //We can use BFS having a count of level size with number of elements in the queue and travesing only till that cnt
23
+ public List <Double > averageOfLevels (TreeNode root ) {
24
+ List <Double > res = new ArrayList <>();
25
+ Queue <TreeNode > q = new LinkedList <>();
26
+ if (root ==null ) {
27
+ return res ;
28
+ }
29
+ q .add (root );
30
+ while (!q .isEmpty ()) {
31
+ int levelSize =q .size ();
32
+ double avg =0 ,cnt =0 ;
33
+ for (int i =0 ;i <levelSize ;i ++) {
34
+ TreeNode tn =q .poll ();
35
+ if (tn .left !=null ) {
36
+ q .add (tn .left );
37
+ }
38
+ if (tn .right !=null ) {
39
+ q .add (tn .right );
40
+ }
41
+ avg +=(double )(tn .val );
42
+ }
43
+ avg /=levelSize ;
44
+ res .add (avg );
45
+ }
46
+ return res ;
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments