-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathSum3.java
More file actions
34 lines (31 loc) · 1000 Bytes
/
pathSum3.java
File metadata and controls
34 lines (31 loc) · 1000 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
return pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int pathSumFrom(TreeNode node, int sum) {
if (node == null) return 0;
return (node.val == sum ? 1 : 0)
+ pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val);
}
}
/*
if(root==null)
return 0;
return (pathSumFrom(root,sum)+pathSumFrom(root.left,sum)+pathSumFrom(root.right,sum));
}
public int pathSumFrom(TreeNode root, int sum)
{
if (root==null) return 0;
return ((root.val==sum?1:0)+pathSumFrom(root.left,sum-root.val)+pathSumFrom(root.right,sum-root.val));
}
*/