Find sum of all left leaves in a given Binary Tree - GeeksforGeeks
Given a Binary Tree, find sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+23+50 = 78.
O(N)
This solution passes in a sum variable as an accumulator. When a left leaf is encountered, the leaf’s data is added to sum.
Read full article from Find sum of all left leaves in a given Binary Tree - GeeksforGeeks
Given a Binary Tree, find sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+23+50 = 78.
O(N)
bool
isLeaf(Node *node)
{
if
(node == NULL)
return
false
;
if
(node->left == NULL && node->right == NULL)
return
true
;
return
false
;
}
// This function returns sum of all left leaves in a given
// binary tree
int
leftLeavesSum(Node *root)
{
int
res = 0;
// Update result if root is not NULL
if
(root != NULL)
{
// If left of root is NULL, then add key of
// left child
if
(isLeaf(root->left))
res += root->left->key;
else
{ // Else recur for left child of root
res += leftLeavesSum(root->left);
}
// Recur for right child of root and update res
res += leftLeavesSum(root->right);
}
// return result
return
res;
}
This solution passes in a sum variable as an accumulator. When a left leaf is encountered, the leaf’s data is added to sum.
/* Pass in a sum variable as an accumulator */
void
leftLeavesSumRec(Node *root,
bool
isleft,
int
*sum)
{
if
(!root)
return
;
// Check whether this node is a leaf node and is left.
if
(root->left==null && root->right==null && isleft)
*sum += root->key;
// Pass 1 for left and 0 for right
leftLeavesSumRec(root->left, 1, sum);
leftLeavesSumRec(root->right, 0, sum);
}