题目链接:https://leetcode-cn.com/problems/sum-of-left-leaves/
题目描述
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
思路
递归。
(1)判断左叶子节点:root->left && !root->left->left && !root->left->right
,root->left
时左叶子节点
(2)递归左右子树
代码
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root)
return 0;
int sum = 0;
if(root->left && !root->left->left && !root->left->right)
sum += root->left->val;
sum += sumOfLeftLeaves(root->left);
sum += sumOfLeftLeaves(root->right);
return sum;
}
};