Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
Solution: Using Recursion
To check if the leaf node is a left left, we can pass bool as param in the function to check if it is a left or right node.
int sumOfLeftLeavesUtil(TreeNode* root, bool isLeft) {
if (!root) return 0;
if (!root->left && !root->right && isLeft) return root->val;
return sumOfLeftLeavesUtil(root->left, true) + sumOfLeftLeavesUtil(root->right, false);
}
int sumOfLeftLeaves(TreeNode* root) {
return sumOfLeftLeavesUtil(root, false);
}