-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution437.java
More file actions
executable file
·46 lines (44 loc) · 1.31 KB
/
Copy pathSolution437.java
File metadata and controls
executable file
·46 lines (44 loc) · 1.31 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.*;
class Solution437 {
public int pathSum(TreeNode root, int targetSum) {
// 把每一个结点作为根结点,遍历
int res = 0;
Stack<TreeNode> s = new Stack<>();
s.push(root);
while (true) {
TreeNode p = s.pop();
res += sum(p, targetSum);
if (p.left != null) s.push(p.left);
if (p.right != null) s.push(p.right);
if (s.isEmpty()) break;
}
return res;
}
public int sum(TreeNode root, int target) {
// 只能dfs
int l = 0, m = 0, r = 0;
if (root.left == null && root.right == null) return root.val == target ? 1 : 0;
// 遍历根节点
if (root.val == target) m = 1;
// 遍历左子树
if (root.left != null) l = sum(root.left, target - root.val);
// 遍历右子树
if (root.right != null) r = sum(root.right, target - root.val);
return l + m + r;
}
}