Sum Root to Leaf Numbers

Advanced

Sum Root to Leaf Numbers

Welcome to the "Sum Root to Leaf Numbers" challenge! Imagine you have a magical tree where each path from the root to a leaf represents a number. Your task is to calculate the sum of all these numbers generated from each root-to-leaf path!

Let's visualize it as follows:

    1
   / \
  2   3

In the above tree, there are two paths:

  • Path 1 (Left): 1 -> 2 which represents the number 12
  • Path 2 (Right): 1 -> 3 which represents the number 13

The sum of these numbers is 12 + 13 = 25.

Another example:

     4
   /   \
  9     0
 / \   \
5   1   6

In this tree, you have:

  • Path 1: 4 -> 9 -> 5 which represents 495
  • Path 2: 4 -> 9 -> 1 which represents 491
  • Path 3: 4 -> 0 -> 6 which represents 406

The sum here is 495 + 491 + 406 = 1392.

Task

You need to implement a function sum_root_to_leaf_numbers that takes a binary tree represented as nested lists and returns the sum of all numbers formed by the root-to-leaf paths.

Example Usage

sum_root_to_leaf_numbers([1, [2], [3]]) # returns 25 sum_root_to_leaf_numbers([4, [9, [5], [1]], [0, [], [6]]]) # returns 1392

The input tree is represented in a list where each list consists of the format [node, left_subtree, right_subtree]. Where left_subtree and right_subtree can be lists themselves or empty [] if there are no children.

Let's solve this tree puzzle and help the numbers flow down from the roots to the leaves! Each number will amaze you with the sum they create together.

Good luck and happy tree climbing!

Geek
Inputs

Arg 1:

[1,[2],[3]]
Expected Output
25
Actual Output