Easy
第一check根結(jié)點(diǎn)的左節(jié)點(diǎn)是不是左葉子節(jié)點(diǎn),是的話就加到res里面,不是的話就對(duì)根結(jié)點(diǎn)的左子樹recursively call sumOfLeftLeaves坯约,一直遞歸到root.left就是左葉子節(jié)點(diǎn)加到res里; 左邊看完了對(duì)根結(jié)點(diǎn)的右子樹直接recursively call 這個(gè)function,也比較好理解卿闹,就是把右子樹完全看成一棵樹求它的左葉子節(jié)點(diǎn)和。其實(shí)這里的base case就是root.left 是leave left node這種情況萝快。
/**
* 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 res = 0;
if (root == null){
return res;
}
if (root.left != null && root.left.left == null && root.left.right == null){
res += root.left.val;
} else {
res += sumOfLeftLeaves(root.left);
}
res += sumOfLeftLeaves(root.right);
return res;
}
}