Ctrl K

Path Totals in a Coded Tree

Medium
A binary tree of depth at most 4 is written as a list codes of three-digit numbers, one per node: - the hundreds digit is the node's depth d (the root is at depth 1, 1 ≤ d ≤ 4); - the tens digit is the node's position p within its row as if the tree were complete (1 ≤ p ≤ 2^(d-1), left to right); - the units digit is the node's value v (0 ≤ v ≤ 9). So the children of the node at position p sit one level deeper at positions 2p - 1 (left) and 2p (right). For every leaf, add up the values on the path from the root to it, and return the grand total over all leaves. The input is guaranteed to describe a valid connected tree.
Example 1
codes=[117, 212, 224, 325] → 25

The root 7 has children 2 and 4; node 2 has a right child 5 (position 2 at depth 3). The leaves are 5 and 4: the paths give 7 + 2 + 5 = 14 and 7 + 4 = 11, 25 in total.

Example 2
codes=[110] → 0

A single root holding 0: one path summing to 0.

Example 3
codes=[113, 229, 343, 488] → 23
Constraints
  • 1 ≤ len(codes) ≤ 15
  • 110 ≤ codes[i] ≤ 489
  • codes is sorted in ascending order
  • codes describes a valid binary tree of depth at most 4
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree From Pre-Order and In-Order Walks MediumTree From In-Order and Post-Order Walks MediumTree Columns, Top Down MediumMost Common Subtree Total MediumStop a Process Branch Medium
loading Python…
Input
codes=[117, 212, 224, 325]
Expected
25

Run checks the first 3 tests in your browser. Submit checks all 115 tests on the server, hidden ones included.