forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSumOfLeftLeaves.java
43 lines (35 loc) · 1.08 KB
/
SumOfLeftLeaves.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
import java.util.Stack;
public class SumOfLeftLeaves {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
int left = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
left = root.left.val;
} else {
left = sumOfLeftLeaves(root.left);
}
return left + sumOfLeftLeaves(root.right);
}
/**
* 迭代法,遍历所有结点,判断是左叶子时加上
*/
public int sumOfLeftLeaves2(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
int sum = 0;
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
root = root.right;
}
}
return sum;
}
}