forked from AntDuPar/Codesignal-Leetcode-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhasPathWithGivenSum.java
43 lines (41 loc) · 1015 Bytes
/
hasPathWithGivenSum.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
/*
Given a binary tree t and an integer s, determine whether there is a root to leaf path in t such that the sum of vertex values equals s.
*/
//
// Definition for binary tree:
// class Tree<T> {
// Tree(T x) {
// value = x;
// }
// T value;
// Tree<T> left;
// Tree<T> right;
// }
boolean hasPathWithGivenSum(Tree<Integer> t, int s) {
if(t == null){
return false;
}
return traverseTree(t, 0, s);
}
boolean checkB = false;
boolean traverseTree(Tree<Integer> tree, int sum, int check){
int tmpSum = sum;
tmpSum += tree.value;
if(checkB == true){
return true;
}
if(tmpSum == check && tree.left == null && tree.right == null){
checkB = true;
return true;
}
if(tmpSum == check){
System.out.println(tree.value);
}
if(tree.left != null){
checkB = traverseTree(tree.left, tmpSum, check);
}
if(tree.right != null){
checkB = traverseTree(tree.right, tmpSum, check);
}
return checkB;
}