Leetcode 404. Sum of Left Leaves

 

 

要实现得到左叶子节点的和,我们加一个bool leftLeaf,代表左叶子,递归的时候,加上这个属性,就可以求得和

/**
 * 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) {
        int sum = 0;
        sumOfLeftLeaves(root, sum, true);
        return sum;
    }
    void sumOfLeftLeaves(TreeNode* root, int& sum, bool leftLeaf) {
        if(!root) return;
        if(!root->left && !root->right && leftLeaf) sum += root->val;
        sumOfLeftLeaves(root->left, sum, true);
        sumOfLeftLeaves(root->right, sum, false);
    }
};

 

posted @ 2020-02-07 06:15  SteveYu  阅读(85)  评论(0编辑  收藏  举报