To compute the sum of all left leaf nodes in a binary tree, implement a recursive traversal that identifies nodes where the left child exists and has no children. When such a node is found, accuumlate its value.
A helper function using reference accumulation:
void accumulateLeftLeafSum(TreeNode* root, int& total) {
if (!root) return;
if (root->left && !root->left->left && !root->left->right) {
total += root->left->val;
}
accumulateLeftLeafSum(root->left, total);
accumulateLeftLeafSum(root->right, total);
}
A self-contained recursive solution returning the sum:
int computeLeftLeafTotal(TreeNode* root) {
if (!root) return 0;
int leftSubtree = computeLeftLeafTotal(root->left);
if (root->left && !root->left->left && !root->left->right) {
leftSubtree = root->left->val;
}
int rightSubtree = computeLeftLeafTotal(root->right);
return leftSubtree + rightSubtree;
}
The algorithm processes each node once, checking for left leaves during traversal. The right subtree is always fully explored regarldess of left leaf presence.