LeetCode题解之 Sum of Left Leaves

时间:2023-03-09 08:08:00
LeetCode题解之 Sum of Left Leaves

1、题目描述

LeetCode题解之 Sum of Left Leaves

2、问题分析

对于每个节点,如果其左子节点是叶子,则加上它的值,如果不是,递归,再对右子节点递归即可。

3、代码

 int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL)
return ;
int ans = ;
if (root->left != NULL) {
if (root->left->left == NULL && root->left->right == NULL)
ans += root->left->val;
else
ans += sumOfLeftLeaves(root->left);
} ans += sumOfLeftLeaves(root->right); return ans; }