题目

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.

代码

通过递归

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int sum=0;
//如果为null直接返回0
if(root==null){
return 0;
}
//如果左子树不为空
if(root.left!=null){
//判断此左子树是否子树
if(root.left.left==null&&root.left.right==null){
sum+=root.left.val;
}else{
//如果此左子树还拥有子树,继续向下
sum+=sumOfLeftLeaves(root.left);
}
}
//当左树判断完以后判断右树
sum+=sumOfLeftLeaves(root.right);
return sum;
}
}