天天看點

*LeetCode遞歸 二叉樹404左葉子之和

問題描述

*LeetCode遞歸 二叉樹404左葉子之和

代碼實作

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root==NULL) return 0;
        if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL)  return sumOfLeftLeaves(root->right)+root->left->val;
        return  sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
    }
};