404.左叶子之和
思路
两种都是基于深搜递归
1.递归查找每个节点满足左子树不为空且左子树为叶子节点的值(if (root.left!=null && root.left.left==null && root.left.right==null)
),若满足条件,则将值加入sum中。
2.递归查找每个节点的左子树为叶子节点的值,比较于第一种方法,直接使用boolean参数来判断是否是左节点,将满足条件的值返回。
3.层序遍历也可以做,在出队的每个节点加入方法1中的判断,若满足加入sum即可。
代码
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
int sum = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
sum += sumOfLeftLeaves(root.left);
sum += sumOfLeftLeaves(root.right);
return sum;
}
}
2
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int sum=0;
if(root==null) return sum;
sum+=recur(root.left,true);
sum+=recur(root.right,false);
return sum;
}
public int recur(TreeNode root,boolean flag){
if (root==null) return 0;
if (root.left==null && root.right==null && flag) return root.val;
return recur(root.left,true)+recur(root.right,false);
}
}