java solution with recursive


  • 0
    L
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            ArrayList<TreeNode> nums = new ArrayList<>();
            int sum = 0;
            
            TreeNode dummy = new TreeNode(-1);
            dummy.right = root;
            
            helper(dummy, root, nums);
            for(TreeNode node:nums){
                sum += node.val;
            }
            
            return sum;
        }
        
        public void helper(TreeNode parent, TreeNode curr, ArrayList<TreeNode> nums){
            if(curr==null){
                return;
            }
            
            if(curr == parent.left && curr.left==null && curr.right==null){
                nums.add(curr);
                return;
            }else{
                helper(curr, curr.left, nums);
                helper(curr, curr.right, nums);
            }
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.