Ctrl K

Binary Branches Total

Easy
You are given the root of a binary tree in which every node holds a bit, 0 or 1. Each path from the root down to a leaf spells a binary number, with the root's bit as the most significant and the leaf's bit as the least significant. For example, the path 1 → 1 → 0 means 110₂ = 6. Return the sum of the numbers spelled by all root-to-leaf paths.
Example 1
root=tree_node([1, 0, 1, None, 1]) → 8

The paths are 1 → 0 → 1, which is 101₂ = 5, and 1 → 1, which is 11₂ = 3. The sum is 8.

Example 2
root=tree_node([0, 1, 1, 1]) → 4

The paths 0 → 1 → 1 = 011₂ = 3 and 0 → 1 = 01₂ = 1. The leading zero adds nothing. The sum is 4.

Constraints
  • 1 ≤ number of nodes ≤ 1000
  • Node.val is 0 or 1
  • The answer is less than 2³¹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLeft, Node, Right EasyIdentical Trees EasyMirror-Image Tree EasyTree Height EasyEvenly Grown Tree Easy
loading Python…
Input
root=tree_node([1, 0, 1, None, 1])
Expected
8

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