Sum of Left Leaves
Description
Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const sumOfLeftLeaves = (root) => {
let sum = 0
const aux = (node) => {
if (!node) {
return
}
if (node.left) {
aux(node.left)
}
if (node.left && !node.left.left && !node.left.right) {
sum += node.left.val
}
if (node.right) {
aux(node.right)
}
}
aux(root)
return sum
}