leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

sum-of-left-leaves.dart (1073B)


      1 //Find the sum of all leaves that are left of their parent.
      2 //to do this I used DFS to recurse through the list and if the current node is 
      3 //a leaf it checks if it is left. If it is a left leaf then the stored value of it is
      4 //added onto the total integer. The time complexity of this code is O(n) where n is the number
      5 //of nodes in the tree. 
      6 //Runtime: 266ms Beats: 100%
      7 //Memory: 142.3MB Beats: 100%
      8 
      9 
     10 /**
     11  * Definition for a binary tree node.
     12  * class TreeNode {
     13  *   int val;
     14  *   TreeNode? left;
     15  *   TreeNode? right;
     16  *   TreeNode([this.val = 0, this.left, this.right]);
     17  * }
     18  */
     19 class Solution {
     20   int total = 0;
     21   int sumOfLeftLeaves(TreeNode? root) {
     22       recurse(root ?? new TreeNode(), false);
     23       return total;
     24   }
     25   
     26   void recurse(TreeNode node, bool is_left ){
     27       if(node.left != null){
     28           recurse(node.left ?? new TreeNode(), true);
     29       }
     30       if(node.right != null){
     31           recurse(node.right ?? new TreeNode(), false);
     32       }
     33       if(is_left && node.right == null && node.left == null){
     34           total += node.val;
     35       }
     36   }
     37 
     38 }