LeetCode 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.

分析:

给定一颗二叉树,求左叶子节点的和。

重点在于如何判断左叶子节点,如果一个节点的left存在,且left的left和right都为空,那么我们就可以将这个节点的left->val记录下来。递归处理整颗树即可。

程序:

/**
 * 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;
        int sum = 0;
        if (root->left && !root->left->right && !root->left->left){
            sum = root->left->val;
        }
        return sum + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};
原文地址:https://www.cnblogs.com/silentteller/p/10705474.html