Recursive Simple C++ solution with no helper function.


  • 0
    /**
     * 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) {
            
            // base case
            if(root==NULL)
                return 0;
            
            int sum = 0;
            // if left is leaf, take left value
            TreeNode *leftNode = root->left;
            if(leftNode && leftNode->left == NULL && leftNode->right == NULL)
                sum += leftNode->val;
            
            // calculate for subtree and return sum
            int left = sumOfLeftLeaves(root->left);
            int right = sumOfLeftLeaves(root->right);
            
            return sum+left+right;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.