Can someone help me understand why my solution is not passing a particular test case?


  • 0
    M

    Here is my code in C#:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int SumOfLeftLeaves(TreeNode root) {
            if(root == null) return 0;
            
            var sum = 0;
            
            if(root.left != null) {
                sum += root.left.val + SumOfLeftLeaves(root.left);
            }
            
            if(root.right != null) {
                sum += SumOfLeftLeaves(root.right);
            }
            
            return sum;
        }
    }
    

    Upon submitting the solution, it appears to be failing the following test case:

    Input: [1,2,3,4,5]
    Output: 6
    Expected: 4
    

  • 0
    V

    @moon

    if(root.left != null) {
                sum += root.left.val + SumOfLeftLeaves(root.left);
            }
    the above line of yours adds every left child whether it was a leaf or not. 
    you are only supposed to add a left leaf value. So in your case, you are adding all left children starting from root, (2+4). which is not right.

Log in to reply
 

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