代码简洁,递归核心是判断条件:左叶子之和,那只要找到左子节点是叶子节点的判断条件即可
c++实现
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
// write code here
if(!root) return 0;
int sum_num=0;
//判断条件:如果左子节点是叶子节点,则再加上右子树的左叶子之和即可
if(root->left && !root->left->left && !root->left->right){
sum_num = root->left->val;
sum_num += sumOfLeftLeaves(root->right);
return sum_num;
}else{ //如果左子节点不是叶子节点,就要将左右子树的左叶子之和相加
sum_num += sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
return sum_num;
}
}
};