Skip to content

Commit f3208c8

Browse files
author
zongyanqi
committed
add Easy_404_Sum_of_Left_Leaves
1 parent 6ed7ce9 commit f3208c8

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Easy_404_Sum_of_Left_Leaves.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Find the sum of all left leaves in a given binary tree.
3+
4+
Example:
5+
6+
3
7+
/ \
8+
9 20
9+
/ \
10+
15 7
11+
12+
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
13+
*
14+
*/
15+
16+
/**
17+
* Definition for a binary tree node.
18+
* function TreeNode(val) {
19+
* this.val = val;
20+
* this.left = this.right = null;
21+
* }
22+
*/
23+
24+
/**
25+
* @param {TreeNode} root
26+
* @return {number}
27+
*/
28+
var sumOfLeftLeaves = function (root) {
29+
return fn(root, false);
30+
};
31+
32+
function fn(node, isLeft) {
33+
if (!node) return 0;
34+
if (!node.left && !node.right) {
35+
return isLeft ? node.val : 0;
36+
}
37+
38+
return fn(node.left, true) + fn(node.right, false);
39+
40+
}
41+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy