Skip to content

Commit 20f20c6

Browse files
refactor 404
1 parent ecd7f7b commit 20f20c6

File tree

1 file changed

+28
-23
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-23
lines changed

src/main/java/com/fishercoder/solutions/_404.java

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package com.fishercoder.solutions;
22

33
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.
58
69
Example:
710
@@ -13,33 +16,35 @@
1316
1417
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.*/
1518
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);
2026
}
21-
return dfs(root, result, false);
22-
}
2327

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;
3844
}
39-
return leftResult + rightResult;
4045
}
4146

42-
private class Solution2 {
47+
public static class Solution2 {
4348

4449
public int sumOfLeftLeaves(TreeNode root) {
4550
int sum = 0;

0 commit comments

Comments
 (0)