-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPathSum.scala
More file actions
44 lines (32 loc) · 1.12 KB
/
Copy pathPathSum.scala
File metadata and controls
44 lines (32 loc) · 1.12 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
/**
* Definition for a binary tree node.
* class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
* var value: Int = _value
* var left: TreeNode = _left
* var right: TreeNode = _right
* }
*/
object Solution {
def checkSum(curr : TreeNode,
accumulator: Int,
targetSum : Int): Boolean = {
if (curr == null) {
return false;
}
// there's no += in scala
if ((accumulator+curr.value) == targetSum && curr.left == null && curr.right == null) {
return true;
}
return checkSum(curr.left, (accumulator+curr.value), targetSum) || checkSum(curr.right, (accumulator+curr.value), targetSum);
}
def hasPathSum(root: TreeNode, targetSum: Int): Boolean = {
if (root == null){
return false;
}
if (root.value == targetSum && root.left == null && root.right == null) {
return true;
}
var accumulator = root.value
return checkSum(root.left, accumulator, targetSum) || checkSum(root.right, accumulator, targetSum);
}
}