max-level-sum-of-binary-tree.dart (1224B)
1 //Given a binary tree return the layer with the greatest 2 //value where the value is the sum of all nodes on that layer. 3 4 //First I did DFS to create a layer list. Normally people do this with 5 //BFS, but leetcode does not have priority queues in dart so this is technically faster. 6 //Then from there I found the layer with the highest sum and returned the index of it + 1. 7 8 //Time: 393ms Beats: 100% 9 //Memory: 181.5MB Beats: 100% 10 11 class Solution { 12 List<List<int>> layers = []; 13 int maxLevelSum(TreeNode? root) { 14 recurse(0, root); 15 int max = -200000000; 16 int max_layer = 1; 17 int layer_count = 1; 18 print(layers); 19 for(var list in layers){ 20 int current = 0; 21 for(int val in list){ 22 current += val; 23 } 24 if(current > max){ 25 max = current; 26 max_layer = layer_count; 27 } 28 layer_count += 1; 29 } 30 return max_layer; 31 } 32 33 void recurse(int depth, TreeNode? root){ 34 if(root == null){ 35 return; 36 } 37 if(depth >= layers.length){ 38 layers.add([]); 39 } 40 layers[depth].add(root.val); 41 recurse(depth+ 1 ,root.left); 42 recurse(depth + 1 ,root.right); 43 } 44 }