wonder what is a better way to track the result if I don't pass it in as a list


  • 0
    Y

    public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
    //int result=0;
    int[] result=new int [1];
    result[0]=0;
    if(root==null||(root.left==null&&root.right==null))
    {
    return 0;
    }
    helper(root,result,true);
    return result[0];
    }

    public void helper(TreeNode root, int[] result, boolean left)
    {
        if(root==null)
        {
            return;
        }
        if(root.left==null&&root.right==null&&left)
        {
            result[0]+=root.val;
            return;
        }
        helper(root.left,result,true);
        helper(root.right,result,false);
    }
    

    }


  • 0
    Y

    I mean I can make it do divide and conquer to return an int, but if I want to it recursive to return a void in the helper, feel like the way I am doing is not the most efficient one.


  • 0
    Y

    divide and conquer solution:
    public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {

       if(root==null)
       {
           return 0;
       }
       
       return helper(root,false);
    }
    
    public int helper(TreeNode root, boolean left)
    {
       if(root==null)
       {
           return 0;
       }
       if(root.left==null&&root.right==null&&left)
       {
           return root.val;
       }
       
       return helper(root.left,true)+helper(root.right,false);
    }
    

    }


Log in to reply
 

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