binary-tree-paths.dart (953B)
1 //Find all paths to every leaf in a binary tree and return them as a string. 2 //The time complexity of this code is O(n) where n is the number of nodes in the tree. 3 //Time: 261ms Beats: 100% 4 //Memory: 142.6MB Beats: 100% 5 6 class Solution { 7 List<String> binaryTreePaths(TreeNode? root) { 8 recurse(root, ""); 9 return leaves; 10 } 11 List<String> leaves = []; 12 void recurse(TreeNode? root , String path){ 13 String add = "->"; 14 if(path == ""){ 15 add = ""; 16 } 17 if(root?.left == null && root?.right == null){ 18 path += add + (root?.val ?? 0).toString(); 19 leaves.add(path); 20 return; 21 } 22 else{ 23 24 if(root?.right != null){ 25 recurse(root?.right , path + add + (root?.val ?? 0).toString()); 26 } 27 if(root?.left != null){ 28 recurse(root?.left, path + add + (root?.val ?? 0).toString()); 29 30 } 31 } 32 } 33 }