File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments