Repository navigation
Expand file tree
/
Copy pathPathSum.java
More file actions
95 lines (76 loc) · 1.72 KB
/
Copy pathPathSum.java
File metadata and controls
95 lines (76 loc) · 1.72 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
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
82
83
84
85
86
87
88
89
90
91
92
93
package LeetCode;
public class PathSum {
public static void main(String args[]) throws Exception
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(3);
root.right = new TreeNode(4);
root.right.left = new TreeNode(6);
System.out.println(hasPathSum(root, 6 ));
System.out.println(hasPathSum(root, 20 ));
System.out.println(hasPathSum(null, 0 ));
root = new TreeNode(1);
root.left = new TreeNode(2);
System.out.println(hasPathSum(root, 1 ));
}
public static boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
{
return false;
}
else
{
return hasPathSum2(root, sum) ;
}
}
public static boolean hasPathSum2(TreeNode root, int sum) {
boolean result = true;
if ( root == null)
{
if (sum == 0)
{
result = true;
}
else
{
result = false;
}
}
else
{
if (root.left != null && root.right != null)
{
result = (hasPathSum2(root.left, (sum - root.val)) || hasPathSum2(root.right, (sum - root.val)));
}
else if (root.left != null)
{
//System.out.println("Reached here man " + (sum - root.val));
result = (hasPathSum2(root.left, (sum - root.val)));
}
else if (root.right != null)
{
result = (hasPathSum2(root.right, (sum - root.val)));
}
else
{
if ((sum - root.val) == 0)
{
result = true;
}
else
{
result = false;
}
}
}
return result;
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}