Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

404. Sum of Left Leaves 🌟

Given the root of a binary tree, return the sum of all left leaves.

Simple recursive dfs

Code

class Solution{
    int dfs(TreeNode *root, bool isLeft){
        if (!root) return 0;
        if (root->left == NULL && root->right == NULL){
            if (isLeft)
                return root->val;
            else
                return 0;
        }
        return dfs(root->left, true) + dfs(root->right, false);
    }

public:
    int sumOfLeftLeaves(TreeNode *root){
        if (!root) return 0;
        return dfs(root, false);
    }
};