Intuitive short C++ solution


  • 0
    G
        bool is_leaf(TreeNode* node) { return (node && !node->left && !node->right); }
        void dfs(TreeNode* root, int* l_sum, bool is_left_child) {
            if (!root) return;
            if (is_leaf(root) && is_left_child) *l_sum += root->val;
            else {
                dfs(root->left, l_sum, true);
                dfs(root->right, l_sum, false);
            }
        }
        int sumOfLeftLeaves(TreeNode* root) {
            int l_sum = 0;
            dfs(root, &l_sum, false /* is_left_child */);
            return l_sum;
        }
    

Log in to reply
 

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