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
|
# Path Sum
#
# You are given a binary tree and a sum, write a script to find if the tree has
# a path such that adding up all the values along the path equals the given
# sum. Only complete paths (from root to leaf node) may be considered for a
# sum.
#
# Example
#
# Given the below binary tree and sum = 22,
#
# 5
# / \
# 4 8
# / / \
# 11 13 9
# / \ \
# 7 2 1
#
# For the given binary tree, the partial path sum 5 → 8 → 9 = 22 is not valid.
#
# The script should return the path 5 → 4 → 11 → 2 whose sum is 22.
class Node {
has Node $.left;
has Node $.right;
has $.value;
}
# This subroutine returns all possible full path sums.
sub path-sum($tree, $sum) {
if ($tree.value == $sum) {
if ($tree.left || $tree.right) {
return [];
} else {
return [[$tree.value],];
}
}
my @ret = [];
if ($tree.left) {
for path-sum($tree.left, $sum - $tree.value) -> @r {
@ret.push([$tree.value, |(@r)]);
}
}
if ($tree.right) {
for path-sum($tree.right, $sum - $tree.value) -> @r {
@ret.push([$tree.value, |(@r)]);
}
}
return @ret;
}
my Node $tree .= new(
value => 5,
left => Node.new(
value => 4,
left => Node.new(
value => 11,
left => Node.new(
value => 7),
right => Node.new(
value => 2))),
right => Node.new(
value => 8,
left => Node.new(
value => 13),
right => Node.new(
value => 9,
right => Node.new(
value => 1))));
for path-sum($tree, 22) -> @full-path {
say @full-path.join(' -> ');
}
|