-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
46 lines (40 loc) · 942 Bytes
/
Copy pathPathSum.java
File metadata and controls
46 lines (40 loc) · 942 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
34
35
36
37
38
39
40
41
42
43
44
45
46
package bts;
class Root {
int data;
Root left, right;
Root(int item)
{
data = item;
left = right = null;
}
}
class PathSum {
Root root;
boolean hasPathSum(Root node, int sum)
{
boolean ans = false;
int subSum = sum - node.data;
if(subSum == 0 && node.left == null && node.right == null)
return(ans = true);
if(node.left != null)
ans = ans || hasPathSum(node.left, subSum);
if(node.right != null)
ans = ans || hasPathSum(node.right, subSum);
return(ans);
}
public static void main(String args[])
{
int sum = 14;
PathSum tree = new PathSum();
tree.root = new Root(10);
tree.root.left = new Root(8);
tree.root.right = new Root(2);
tree.root.left.left = new Root(3);
tree.root.left.right = new Root(5);
tree.root.right.left = new Root(2);
if (tree.hasPathSum(tree.root, sum))
System.out.println("true");
else
System.out.println("false");
}
}