sum of left leaves in a tree(leetcode).
sum of left leaves in a tree(leetcode).
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root)
{
queue<TreeNode *>q;
int sum=0;
if(root==NULL)
return 0;
else if(root->left==NULL && root->right==NULL)
return 0;
else
{
q.push(root);
while(!q.empty())
{
TreeNode * x;
x=q.front();
q.pop();
if(x->left!=NULL)
{
if(x->left->left==NULL && x->left->right==NULL)
sum=sum+x->left->val;
}
if(x->left!=NULL)
q.push(x->left);
if(x->right!=NULL)
q.push(x->right);
}
return sum;
}
}
};
Comments
Post a Comment