KatInterview

Total Value of Bit-Strings Along a Tree's Leaf Paths

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbinary-treedfsbfs

Last updated

Decode a level-order bit tree with skipped None slots, then sum the binary values read along each root-to-leaf path, testing BFS parsing and DFS with a running accumulator.

A binary tree stores a single bit (0 or 1) in each node. Walking from the root down to any leaf produces a string of bits. Treat that string as a binary number, where the root's bit is the most significant digit. For instance, the walk 1 -> 1 -> 0 gives binary 110, which equals 6.

Your task is to compute the total of the numbers produced by every root-to-leaf walk.

Input format

The tree is given as a list tree in level-order form:

  • tree[0] is the value of the root.
  • After that, the entries are consumed in consecutive pairs. Each node that is not None takes one pair, and nodes are served in the order in which they appear in the list (first the root, then the real nodes in the order they were listed, and so on).
  • In each pair, the first entry is that node's left child and the second is its right child. A None entry means that child does not exist.
  • A None entry is just a placeholder: it does not get a pair of its own.
  • Trailing None values may be left out. If the list ends before a node's pair is read, that node (and every node after it in the order) has no children. If only one entry of a pair remains, it is the left child and the right child is absent.

Rules

  • A leaf is a node with no children. Each leaf ends exactly one path.
  • A node with exactly one child is not a leaf.
  • Leading zeros are fine: the walk 0 -> 1 -> 1 is binary 011, which equals 3.
  • If the root has no children, there is one path, and the answer is the root's bit.

Task

Return the sum of the values of all root-to-leaf paths as an integer.

Constraints

  • The tree has between 1 and 1,000 nodes, and 1 <= len(tree) <= 2001.
  • tree[0] is never None.
  • Every non-None entry is 0 or 1.
  • Each root-to-leaf path has at most 31 nodes, so each path value is at most 2^31 - 1.
  • The expected answer is guaranteed to be at most 2^31 - 1.

Examples

Example 1

Input: sum_leaf_path_values([1, 1, 0, None, 1, 1])

Output: 12

Example 2

Input: sum_leaf_path_values([1, 0, None, 0, 1])

Output: 9

Example 3

Input: sum_leaf_path_values([0])

Output: 0

Hints

Hint 1

Before worrying about the sum, think about how to rebuild the tree. Heap-style indexing (children at 2i+1 and 2i+2) fails when None entries appear; consider a queue that holds only the real nodes.

Hint 2

When you step from a parent to a child, the number spelled so far changes by a simple rule: shift it left one bit and add the child's bit, i.e. value = value * 2 + bit.

Hint 3

Add the running value to the answer only at nodes that have neither a left nor a right child. A node with just one child must keep going down.