计算给定二叉树的所有左叶子之和。
示例:
    3
   / \
  9  20
    /  \
   15   7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24。

详见:https://leetcode.com/problems/sum-of-left-leaves/description/

C++:

方法一:

/**
 * 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||!root->left&&!root->right)
        {
            return 0;
        }
        int res=0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty())
        {
            root=que.front();
            que.pop();
            if(root->left&&!root->left->left&&!root->left->right)
            {
                res+=root->left->val;
            }
            if(root->left)
            {
                que.push(root->left);
            }
            if(root->right)
            {
                que.push(root->right);
            }
        }
        return res;
    }
};

 方法二:

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