Problem 418193 · medium · Level 04 Non-Linear Data Structures

Adding Up the Branch Codes

binary tree · recursion · arithmetic

Each node of a binary tree holds one digit 0-9. Reading the digits from the root down to a leaf, root first, gives a decimal number: the code of that branch. Return the total of the codes of all the branches. An empty tree totals 0.

Examples

    3
   / \
  5   2
 / \
1   8

Input:  root = build_tree([3, 5, 2, 1, 8])
Output: 741
Explanation: 351 + 358 + 32 = 741.

Input:  root = build_tree([6, 0, 7])
Output: 127

Constraints

  • 0 <= number of nodes <= 1000
  • 0 <= node.val <= 9
  • The tree depth is at most 12 in the visible tests, but Python integers make depth irrelevant.

Goals

  • Build a number digit by digit while descending
  • Combine results from both subtrees at a leaf boundary
Starting Python…