In this Leetcode Sum of Left Leaves problem solution we have given the root of a binary tree, return the sum of all left leaves.

Leetcode Sum of Left Leaves problem solution


Problem solution in Python.

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.ans=0
        self.findleftleaves(root)
        return self.ans
        
    def findleftleaves(self,root):
        if not root:
            return
        if root.left and self.isLeaves(root.left):
            self.ans+=root.left.val
        self.findleftleaves(root.left)
        self.findleftleaves(root.right)
        return 
            
    def isLeaves(self,root):
        return root.left==None and root.right==None



Problem solution in Java.

public int sumOfLeftLeaves(TreeNode root) {
	if (root == null) return 0;

	int sum = 0;
	if (root.left != null && root.left.left == null && root.left.right == null) {
		sum = root.left.val;
	}

	return sum + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}


Problem solution in C++.

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
       if(root == nullptr) 
           return 0;
    
       int sum = 0;
       queue<pair<TreeNode*, bool>> q;
        
       q.push({root, false});
       while(!q.empty())
       {
           pair<TreeNode*, bool> p = q.front();
           q.pop();
           TreeNode *node = p.first;
           bool bIsLeftNode = p.second;
           
           if(node->left)
           {
               q.push({node->left, true});
           }
           if(node->right)
           {
               q.push({node->right, false});
           }
           
           if(bIsLeftNode && node->left == nullptr && node->right == nullptr)
           {
               sum+= node->val;
           }
       }
        return sum;
    }
};


Problem solution in C.

void countleft(struct TreeNode* root,int *sum)
{
       if(root==NULL) {
           return;
       }
    if(root->left == NULL && root->right == NULL)
       *sum= *sum+root->val;    

}

void traverse(struct TreeNode* root,int *sum)
{
    if(root==NULL) {
        return;
    }
    traverse(root->left,sum);
    countleft(root->left,sum);
    traverse(root->right,sum);
}

int sumOfLeftLeaves(struct TreeNode* root){
      int sum=0;
      if(root==NULL || (root->left == 0 && root->right==0)) {
          return 0;
      }
      traverse(root,&sum);
      return sum;
}