How to calculate the sum of the left leaves of a binary tree

Given a binary tree. Calculate the sum of the left leaves

Example

binary tree

 

Output: 7

 

/* Definition for TreeNode
public class TreeNode
{
    public int Value;
    public TreeNode Left;
    public TreeNode Right;

    public TreeNode(int value)
    {
        Value = value;
    }
}
*/

public sealed class Solution
{
    public int LeftLeavesSum(TreeNode root)
    {
    }
}

Approach

To solve this problem we need to find out all left leaves. A leaf is a node without child nodes. To find all left leaves we can use one of the binary traversal algorithms with a small modification, we need to track is a left leaf or not. If a leaf is a left leaf we need to update a sum

 

Code

public int LeftLeavesSum(TreeNode root)
{
    var result = new int[1];
    Sum(root, false, result);
    return result[0];
}

private void Sum(TreeNode root, bool isLeft, int[] result)
{
    if (root == null)
    {
        return;
    }

    if (isLeft && root.Left == null && root.Right == null)
    {
        result[0] += root.Value;
    }

    Sum(root.Left, true, result);
    Sum(root.Right, false, result);
}