力扣简单递归:左叶子之和

时间:2024-02-29 14:20:21

思路:重点在于每层都记录val的值以减少递归调用次数

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


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