-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_404.java
79 lines (71 loc) · 1.85 KB
/
leetcode_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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package leetcode;
import java.util.Deque;
import java.util.LinkedList;
/*
左右子树之和
*/
public class leetcode_404 {
}
class lee_404{
/**
* 深度优先遍历
* @param root
* @return
*/
public int sumOfLeftLeaves(TreeNode root) {
if(root == null)
return 0;
return zijiedian(root);
}
private int zijiedian(TreeNode node){
int res = 0;
if(node.left != null){
TreeNode tleft = node.left;
if(tleft.left == null && tleft.right == null){
res+=tleft.val;
}else {
res += zijiedian(tleft);
}
}
if(node.right != null){
TreeNode treeNode = node.right;
if(treeNode.left !=null || treeNode.right!= null)
res += zijiedian(treeNode);
}
return res;
}
}
class lee_404_2 {
/**
* 广度优先遍历
*
* @param root
* @return
*/
public int sumOfLeftLeaves(TreeNode root) {
if(root == null)
return 0;
int res = 0;
Deque<TreeNode> deque = new LinkedList<TreeNode>();
deque.addFirst(root);
while(!deque.isEmpty()){
TreeNode node = deque.pollLast();
if(node.left != null) {
if (isLeafNode(node.left)) {
res += node.left.val;
} else {
deque.addFirst(node.left);
}
}
if (node.right != null) {
if (!isLeafNode(node.right)) {
deque.addFirst(node.right);
}
}
}
return res;
}
public boolean isLeafNode(TreeNode node) {
return node.left == null && node.right == null;
}
}