原题
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
代码实现
public class LeftLeafSum
{
public int SumOfLeftLeaves(TreeNode root)
{
if (root == null)
return 0;
int sum=0;
if (root.left!=null && isLeaf(root.left))//左叶子
sum += root.left.val;
sum += SumOfLeftLeaves(root.left);
sum += SumOfLeftLeaves(root.right);
return sum;
}
private bool isLeaf(TreeNode node)
{
return node.left == null && node.right == null;
}
}