forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_404.java
54 lines (49 loc) · 1.54 KB
/
_404.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _404 {
public static class Solution1 {
public int sumOfLeftLeaves(TreeNode root) {
int result = 0;
if (root == null) {
return result;
}
return dfs(root, result, false);
}
private int dfs(TreeNode root, int result, boolean left) {
if (root.left == null && root.right == null && left) {
result += root.val;
return result;
}
int leftResult = 0;
if (root.left != null) {
left = true;
leftResult = dfs(root.left, result, left);
}
int rightResult = 0;
if (root.right != null) {
left = false;
rightResult = dfs(root.right, result, left);
}
return leftResult + rightResult;
}
}
public static class Solution2 {
public int sumOfLeftLeaves(TreeNode root) {
int sum = 0;
if (root == null) {
return sum;
}
if (root.left != null) {
if (root.left.left == null && root.left.right == null) {
sum += root.left.val;
} else {
sum += sumOfLeftLeaves(root.left);
}
}
if (root.right != null) {
sum += sumOfLeftLeaves(root.right);
}
return sum;
}
}
}