Two treasure hunters each sketched a branching trail map starting from a single landmark: from any landmark at most two trails continue onward, called the left trail and the right trail, and every landmark records an amount of gold buried there. The hunters want to merge their maps into one: at any position in the branching layout where both maps have a landmark, the merged landmark holds the sum of both gold amounts; at any position where only one map has a landmark, the merged map simply keeps that entire landmark and everything reachable further down its trails, untouched; positions with no landmark in either map stay empty. Given both maps, output the merged map.
null marking a position with no landmark. A landmark's left-trail and right-trail tokens follow later in the same sequence, in the order their landmarks were reached; a null position contributes no further tokens of its own. If the sequence runs out of tokens before a landmark's trail tokens appear, treat those trails as absent. A map with no landmarks at all is written as the single token null.null tokens at the end of the line are, and should be, omitted). Print null if the merged map has no landmarks.-1000 <= gold amount <= 1000.Example 1
Input
1 3 2 5 2 1 3 null 4 null 7
Expected
3 4 5 5 4 null 7
Explanation
Map A is landmark 1 with left trail to 3 (which has a further left trail to 5) and right trail to 2. Map B is landmark 2 with left trail to 1 (which has a further right trail to 4) and right trail to 3 (which has a further right trail to 7). Overlaying: the roots sum to 1+2=3; the left trails sum to 3+1=4, and since only Map A has a landmark further left (5) and only Map B has one further right (4), those are kept as-is; the right trails sum to 2+3=5, with no landmark further left in either map (empty) and only Map B's 7 further right, kept as-is. The result is 3 4 5 5 4 null 7.
Example 2
Input
null 5 2 8
Expected
5 2 8
Explanation
Map A has no landmarks at all, so overlaying simply copies Map B unchanged: landmark 5 with left trail to 2 and right trail to 8, giving 5 2 8.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →