Recursive analysis of a binary tree with memoization
Swift
Hard
functions
Task «Recursive analysis of a binary tree with memoization»
Write a function that takes a binary tree represented as an array of integers (level-order traversal, null is denoted as 0) and returns the maximum sum of node values from the root to a leaf, provided that no more than two consecutive nodes on the path can be skipped. Use a recursive function with memoization for efficient computation. The tree contains up to 1000 nodes, values range from -100 to 100.
Input Format
First line: an integer n (1 ≤ n ≤ 1000) — the number of elements in the array. Second line: n integers separated by spaces — the level-order representation of the tree (0 denotes the absence of a node).
Output Format
One integer — the maximum sum from the root to a leaf, considering the possibility of skipping no more than two consecutive nodes.
Examples
Example 1
INPUT
3
ab
bc
ca
OUTPUT
6
Example 2
INPUT
1
10
OUTPUT
10
Example 3
INPUT
5
10 5 15 0 0
OUTPUT
25
Example 4
INPUT
2
abc
def
OUTPUT
0
main.swift