Write a program to find sum of left leaves in a binary tree

     5
   /  \
  3    10
       / \
      7   8

The answer will be 3 + 7 = 10

This problem can be solved by using preorder traversal where while traversing the node calculate the sum if the node is a leat node.

public int sumOfLeftLeaves(TreeNode root) {
		 sumOfLeftLeaves(root, false);
		 return globalsum;
	}

	private int globalsum = 0;
	
	private void sumOfLeftLeaves(TreeNode root, boolean isLeft) {
		if(root == null)
			return;
		if (isLeft) {
			if (root.left == null && root.right == null) {
				globalsum +=root.val;
			}
		}
		sumOfLeftLeaves(root.left, true);
		sumOfLeftLeaves(root.right, false);
	}

The above approach uses a global variable and it is initialized outside the function. This makes the code look simpler but adds an additional use of variable. This can be fixed by allowing method to maintain sum of each node and traverse the sum.

public int sumOfLeftLeaves(TreeNode root) {
		return sumOfLeftLeaves(root, false, 0);		
	}
	
	public int sumOfLeftLeaves(TreeNode root, boolean isLeft, int sum) {
			if(root == null)
				return 0;
			if (isLeft && root.left == null && root.right == null) {
				return sum + root.val;
			}
			int sumR =0, sumL=0;
			if(root.left != null)  {
				sumL = sumOfLeftLeaves(root.left, true, sum);
			}
			
			if(root.right != null)  {
				sumR = sumOfLeftLeaves(root.right, false, sum);
			}
			return sumL+ sumR;
	}