forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
81 lines (63 loc) · 1.93 KB
/
Solution.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
80
81
/// Source : https://leetcode.com/problems/path-sum-iii/description/
/// Author : liuyubobobo
/// Time : 2017-11-18
/// Recursive
/// Time Complexity: O(n), where n is the node's number of the tree
/// Space Complexity: O(h), where h is the height of the tree
class Solution {
/// Definition for a binary tree node.
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public int pathSum(TreeNode root, int sum) {
if(root == null)
return 0;
return findPath(root, sum)
+ pathSum(root.left , sum)
+ pathSum(root.right , sum);
}
private int findPath(TreeNode node, int num){
if(node == null)
return 0;
int res = 0;
if(node.val == num)
res += 1;
res += findPath(node.left , num - node.val);
res += findPath(node.right , num - node.val);
return res;
}
public static void main(String[] args) {
/*****************
* Test case:
*
* 10
* / \
* 5 -3
* / \ \
* 3 2 11
* / \ \
* 3 -2 1
*****************/
TreeNode node1 = new TreeNode(3);
TreeNode node2 = new TreeNode(-2);
TreeNode node3 = new TreeNode(3);
node3.left = node1;
node3.right = node2;
TreeNode node4 = new TreeNode(1);
TreeNode node5 = new TreeNode(2);
node5.right = node4;
TreeNode node6 = new TreeNode(5);
node6.left = node3;
node6.right = node5;
TreeNode node7 = new TreeNode(11);
TreeNode node8 = new TreeNode(-3);
node8.right = node7;
TreeNode node9 = new TreeNode(10);
node9.left = node6;
node9.right = node8;
System.out.println((new Solution()).pathSum(node9, 8));
}
}