|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import com.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 | public class _404 {
|
16 |
| - public int sumOfLeftLeaves(TreeNode root) { |
17 |
| - int result = 0; |
18 |
| - if (root == null) { |
19 |
| - return result; |
| 19 | + public static class Solution1 { |
| 20 | + public int sumOfLeftLeaves(TreeNode root) { |
| 21 | + int result = 0; |
| 22 | + if (root == null) { |
| 23 | + return result; |
| 24 | + } |
| 25 | + return dfs(root, result, false); |
20 | 26 | }
|
21 |
| - return dfs(root, result, false); |
22 |
| - } |
23 | 27 |
|
24 |
| - private int dfs(TreeNode root, int result, boolean left) { |
25 |
| - if (root.left == null && root.right == null && left) { |
26 |
| - result += root.val; |
27 |
| - return result; |
28 |
| - } |
29 |
| - int leftResult = 0; |
30 |
| - if (root.left != null) { |
31 |
| - left = true; |
32 |
| - leftResult = dfs(root.left, result, left); |
33 |
| - } |
34 |
| - int rightResult = 0; |
35 |
| - if (root.right != null) { |
36 |
| - left = false; |
37 |
| - rightResult = dfs(root.right, result, left); |
| 28 | + private int dfs(TreeNode root, int result, boolean left) { |
| 29 | + if (root.left == null && root.right == null && left) { |
| 30 | + result += root.val; |
| 31 | + return result; |
| 32 | + } |
| 33 | + int leftResult = 0; |
| 34 | + if (root.left != null) { |
| 35 | + left = true; |
| 36 | + leftResult = dfs(root.left, result, left); |
| 37 | + } |
| 38 | + int rightResult = 0; |
| 39 | + if (root.right != null) { |
| 40 | + left = false; |
| 41 | + rightResult = dfs(root.right, result, left); |
| 42 | + } |
| 43 | + return leftResult + rightResult; |
38 | 44 | }
|
39 |
| - return leftResult + rightResult; |
40 | 45 | }
|
41 | 46 |
|
42 |
| - private class Solution2 { |
| 47 | + public static class Solution2 { |
43 | 48 |
|
44 | 49 | public int sumOfLeftLeaves(TreeNode root) {
|
45 | 50 | int sum = 0;
|
|
0 commit comments