LeetCode-Java-404. Sum of Left Leaves
原创
©著作权归作者所有:来自51CTO博客作者MC43700000046E4的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目
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;
}
}