Skip to contentKEEP THE CRAFTTHE SANCTUARY

Root-to-Leaf Path Sums

List the sum of every root-to-leaf path by carrying a running total down a DFS.

The problem

Implement root_to_leaf_sums(values, children, root). The tree's nodes are numbered from 0: values[i] is the value of node i, and children[i] lists node i's children from left to right. A leaf is a node with no children. For every path from root down to a leaf, add up the values on that path. Return these sums in depth-first order: finish every path through one child before moving on to the next child. When the tree is empty, root is -1; return [] in that case.

Starter code

def root_to_leaf_sums(values, children, root):
    pass

Public examples

  1. values = [5, 2, 7, 1], children = [[1, 2], [3], [], []], root = 0gives[8, 12]
  2. values = [4], children = [[]], root = 0gives[4]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.