path-sum-ii.dart (843B)
1 //Given a binary tree return every path that adds up to the target sum. 2 //To do this I recursively called the function for branch to see if from root to leaf 3 //added up to the target sum if it did I returned that value back to the parent each time adding 4 //on the current value to the list. 5 //Time: 292ms Beats: 77.78% 6 //Memory: 143.7MB Beats: 77.78% 7 8 class Solution { 9 List<List<int>> pathSum(TreeNode? root, int targetSum) { 10 if(root == null){ 11 return []; 12 } 13 if(targetSum == (root.val) && root.left == null && root.right == null){ 14 return [[root.val]]; 15 } 16 List<List<int>> list = pathSum(root.left, targetSum - root.val); 17 list += pathSum(root.right, targetSum - root.val); 18 for(int i = 0 ; i < list.length ; ++i){ 19 list[i].insert(0,root.val); 20 } 21 return list; 22 } 23 }