Sum of Root To Leaf Binary Numbers

You are given the root of a binary tree where every node holds 0 or 1. Each root-to-leaf path spells a binary number with the most significant bit at the root. Return the sum of the numbers formed by all root-to-leaf paths. The answer fits in a 32-bit integer.

30:00

Sum of Root To Leaf Binary Numbers
easy
Free written solution
Topics
Companies

You are given the root of a binary tree where every node holds 0 or 1. Each root-to-leaf path spells a binary number with the most significant bit at the root. Return the sum of the numbers formed by all root-to-leaf paths. The answer fits in a 32-bit integer.

Example 1:
Input: {"root":[1,0,1,0,1,0,1]}
Output: 22
Constraints:
  • The number of nodes in the tree is in the range [1,1000][1, 1000].

  • Node.val\text{Node.val} is 00 or 11.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,0,1,0,1,0,1]}

Each root-to-leaf path is a binary number, root bit first. Start dfs(root, 0).

1010101

cur = path bits read in binary (each new bit doubles everything before it)

empty

= 0

leaf numbers (0)

none yet

= 0

Variables
VariableValue
node-
cur0
bits-
total0
DepthFunction Call
Stack empty
0/15