天天看點

leetcode404. 左葉子之和

計算給定二叉樹的所有左葉子之和。

示例:

3
   / \
  9  20
    /  \
   15   7
           

在這個二叉樹中,有兩個左葉子,分别是 9 和 15,是以傳回 24

說明:如果一個節點的左子節點不為空,且左子節點沒有子節點,則此左子節點一定是左葉子節點。

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