404. Sum of Left Leaves(C语言)

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

我是看了答案才觉得其实明白了题意,答案也就出来了

求树里面,所有有左孩子,而左孩子没有孩子的这样的左孩子值的和

404. Sum of Left Leaves(C语言)_第1张图片

/**
 * 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;
    }
    if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL){
        return root->left->val+sumOfLeftLeaves(root->right);
    }
    return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}


你可能感兴趣的:(LeetCode,C语言)