KatInterview

Sum of Decimal Paths in a Binary Tree

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsbinary-treebfsdfs

Last updated

Tests depth-first (or breadth-first) traversal of a binary tree while tracking the accumulated digit value along each root-to-leaf path.

Problem Statement

You are given a binary tree where every node holds a single digit (0–9). Reading the digits from the root down to any leaf spells out a decimal number — the root digit is the most significant. For instance, travelling 3 → 1 → 4 produces the number 314.

Your task is to find the total of all such numbers, one per leaf.

The tree arrives as a level-order list (the same serialization format used by most online judges):

  • The root is at index 0.
  • For every non-null node dequeued in BFS order, the next two slots in the list are its left and right children.
  • None marks an absent child.
  • Trailing None values may be left out.

Return 0 for an empty or null-rooted tree.

Leaf Definition

A node is a leaf when both its left and right children are absent (i.e., None). A node with exactly one child is not a leaf; only the child's subtree contributes complete numbers.

Constraints

  • The total number of nodes is in the range [0, 1000].
  • Every node value satisfies 0 ≤ value ≤ 9.
  • The tree depth will not exceed 10 levels.
  • The sum of all path numbers fits in a standard Python integer.

Examples

Example 1

Input: path_digit_sum([1, 2, 3])

Output: 25

Example 2

Input: path_digit_sum([4, 9, 0, 5, 1])

Output: 1026

Example 3

Input: path_digit_sum([0, 1, 2])

Output: 3

Hints

Hint 1

Each time you move one level deeper, the number built so far shifts left by one decimal place: new_number = parent_number * 10 + child_digit. Think about how to carry that running value through your traversal.

Hint 2

Because the input is a level-order list, a BFS queue naturally processes nodes in the same order their child slots appear in the list. Keep a pointer into the list and advance it by two for every node you dequeue.

Hint 3

A node is a leaf only when both child slots are None. Make sure you test each slot with `is None` rather than a truthiness check, or a node with value 0 will be misidentified as absent.