Skip to the code
cf.
+25 XP

#356 Version Codes From Tree Digits

medium

A release tool stores version codes in a tree of digits: reading the digits from the root down to a leaf gives one version code. For example, the path 1 → 0 → 4 is the code 104.

Write sumOfCodes(root) that returns the sum of all the codes formed by root-to-leaf paths. Every node holds a single digit 0-9. The tree has at least one node, and the answer fits in a normal number.

Example 1

Input: root = [1,2,3]
Output: 25

The codes are 12 and 13, and 12 + 13 = 25.

Example 2

Input: root = [4,9,0,5,1]
Output: 1026

The codes are 495, 491, and 40.

Constraints

  • 1 <= number of nodes <= 1000
  • 0 <= digit <= 9
  • Depth is at most 10.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).