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.
sum为所有左枝叶子结点的和,采用DFS递归调用SumOfLeftLeaves(),判断当前结点左子结点非空后,在判断其是否叶子结点,若是则将其值加入sum中,AC码如下:
public class Solution {
int sum=0;
public int sumOfLeftLeaves(TreeNode root) {
if(root==null)return 0;
if(root.left!=null){
if(root.left.left==null && root.left.right==null){
sum+=root.left.val;
}else{
sumOfLeftLeaves(root.left);
}
}
sumOfLeftLeaves(root.right);
return sum;
}
}版权声明:本文为catttbao原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。