C++ solution


  • 0
    Q
    /**
     * 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) {
            int res = 0;
            dfs(root,res,false);
            return res;
        }
        
        void dfs(TreeNode *root, int &sum, bool flag){
            if(root == nullptr)
                return;
            if(!root->left && !root->right){
                if(flag == true)
                    sum += root->val;
                return;
            }
            dfs(root->left, sum,true);
            dfs(root->right, sum,false);
            return;
        }
    };
    

Log in to reply
 

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