|
1 | 1 | packagecom.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | importcom.fishercoder.common.classes.TreeNode;
|
4 |
| -/**Find the sum of all left leaves in a given binary tree. |
| 4 | +/** |
| 5 | + * 404. Sum of Left Leaves |
| 6 | + * |
| 7 | + * Find the sum of all left leaves in a given binary tree. |
5 | 8 |
|
6 | 9 | Example:
|
7 | 10 |
|
|
13 | 16 |
|
14 | 17 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.*/
|
15 | 18 | publicclass_404 {
|
16 |
| -publicintsumOfLeftLeaves(TreeNoderoot) { |
17 |
| -intresult =0; |
18 |
| -if (root ==null) { |
19 |
| -returnresult; |
| 19 | +publicstaticclassSolution1 { |
| 20 | +publicintsumOfLeftLeaves(TreeNoderoot) { |
| 21 | +intresult =0; |
| 22 | +if (root ==null) { |
| 23 | +returnresult; |
| 24 | + } |
| 25 | +returndfs(root,result,false); |
20 | 26 | }
|
21 |
| -returndfs(root,result,false); |
22 |
| - } |
23 | 27 |
|
24 |
| -privateintdfs(TreeNoderoot,intresult,booleanleft) { |
25 |
| -if (root.left ==null &&root.right ==null &&left) { |
26 |
| -result +=root.val; |
27 |
| -returnresult; |
28 |
| - } |
29 |
| -intleftResult =0; |
30 |
| -if (root.left !=null) { |
31 |
| -left =true; |
32 |
| -leftResult =dfs(root.left,result,left); |
33 |
| - } |
34 |
| -intrightResult =0; |
35 |
| -if (root.right !=null) { |
36 |
| -left =false; |
37 |
| -rightResult =dfs(root.right,result,left); |
| 28 | +privateintdfs(TreeNoderoot,intresult,booleanleft) { |
| 29 | +if (root.left ==null &&root.right ==null &&left) { |
| 30 | +result +=root.val; |
| 31 | +returnresult; |
| 32 | + } |
| 33 | +intleftResult =0; |
| 34 | +if (root.left !=null) { |
| 35 | +left =true; |
| 36 | +leftResult =dfs(root.left,result,left); |
| 37 | + } |
| 38 | +intrightResult =0; |
| 39 | +if (root.right !=null) { |
| 40 | +left =false; |
| 41 | +rightResult =dfs(root.right,result,left); |
| 42 | + } |
| 43 | +returnleftResult +rightResult; |
38 | 44 | }
|
39 |
| -returnleftResult +rightResult; |
40 | 45 | }
|
41 | 46 |
|
42 |
| -privateclassSolution2 { |
| 47 | +publicstaticclassSolution2 { |
43 | 48 |
|
44 | 49 | publicintsumOfLeftLeaves(TreeNoderoot) {
|
45 | 50 | intsum =0;
|
|