思路:什么是左叶子节点,对于左叶子节点的父节点cur来说,cur->left!=NULL&&cur->left->left==NULL&&cur->left->right==NULL。这样的话,cur->left就是左叶子节点。
之后的话,就正常递归就行。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int>num;
void getleftleave(TreeNode*cur)
{
if(cur->left&&cur->left->right==NULL&&cur->left->left==NULL)
{
num.push_back(cur->left->val);
}
if(cur->left)getleftleave(cur->left);
if(cur->right)getleftleave(cur->right);
}
int sumOfLeftLeaves(TreeNode* root)
{
getleftleave(root);
if(num.size()==0)return 0;
int sum=0;
for(int i=0;i<num.size();i++)
{
sum+=num[i];
}
return sum;
}
};