-
Notifications
You must be signed in to change notification settings - Fork 0
/
404. 左叶子之和.java
53 lines (46 loc) · 1.18 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
/**
* DFS
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return dfs(root);
}
private int dfs(TreeNode root){
if(root == null){
return 0;
}
int res = 0;
if(root.left != null && root.left.left == null && root.left.right == null){ // 只有 root.left != null 是左子树之和,所有条件是左叶子之和
res += root.left.val;
}
res += dfs(root.left);
res += dfs(root.right);
return res;
}
}
/**
* BFS
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int res = 0;
if(root == null){
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node.left != null && node.left.left == null && node.left.right == null){
res += node.left.val;
}
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
return res;
}
}