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.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Traverse the binary tree with Depth-First Search (DFS) algorithm
* @param {TreeNode} root
* @return {number}
*/
var sumOfLeftLeaves = function(root) {
"use strict";
let sum = 0;
function dfs(node) {
if (node.left) {
if (!node.left.left && !node.left.right) {
sum += node.left.val;
}
dfs(node.left);
}
node.right && dfs(node.right);
}
root && dfs(root);
return sum;
};