-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSumOfLeftLeaves.java
More file actions
47 lines (42 loc) · 1.09 KB
/
SumOfLeftLeaves.java
File metadata and controls
47 lines (42 loc) · 1.09 KB
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
package binary_tree;
/**
* @Author: Wenhang Chen
* @Description:计算给定二叉树的所有左叶子之和。 示例:
* <p>
* 3
* / \
* 9 20
* / \
* 15 7
* <p>
* 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
* @Date: Created in 10:16 3/2/2020
* @Modified by:
*/
public class SumOfLeftLeaves {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public int sumOfLeftLeaves(TreeNode root) {
return sumOfLeftLeavesHelper(root, false);
}
// 先序遍历求所有左叶子节点值之和
public int sumOfLeftLeavesHelper(TreeNode root, boolean flag) {
if (root == null) {
return 0;
}
int leave = 0;
// 左叶子节点
if (flag && root.left == null && root.right == null) {
leave = root.val;
}
int left = sumOfLeftLeavesHelper(root.left, true);
int right = sumOfLeftLeavesHelper(root.right, false);
return left + right + leave;
}
}