404. Sum of Left Leaves

来源:互联网 发布:滚雷行动 知乎 编辑:程序博客网 时间:2024/05/01 00:14

简单的DFS

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