Sum of Root To Leaf Binary Numbers

EasyTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Every node of the given binary tree holds a single bit, 0 or 1. Reading the bits along a path from the root down to a leaf (a node with no children) spells a binary number, with the root as the most significant bit. Return the sum of the numbers spelled by **all** root-to-leaf paths, as a decimal integer. Leading zeros are allowed and simply do not change the value (the path 0 -> 1 is 1). The answer is guaranteed to fit in a 32-bit signed integer. A single DFS carrying the running value runs in O(n) time.

Examples

Input: root = [1,0,1,0,1,0,1]
Output: 22
The paths spell 100, 101, 110, 111 = 4 + 5 + 6 + 7 = 22.
Input: root = [0]
Output: 0
The only path is the single bit 0.

Constraints

  • 1 <= number of nodes <= 1000
  • Node.val is 0 or 1
  • The answer fits in a 32-bit signed integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems