Sum of Root To Leaf Binary Numbers - Problem

Imagine you're walking through a binary tree where each node contains either a 0 or 1. Every path from the root to a leaf represents a binary number, where the most significant bit is at the root.

Your mission: Calculate the sum of all binary numbers formed by root-to-leaf paths.

For example, if you traverse the path 1 β†’ 0 β†’ 1, this represents the binary number 101, which equals 5 in decimal. You need to find all such paths and sum up their decimal values.

The tree structure guarantees that each path creates a unique binary number, and all results fit within a 32-bit integer.

Input & Output

example_1.py β€” Python
$ Input: root = [1,0,1,0,1,0,1]
β€Ί Output: 22
πŸ’‘ Note: The tree has 4 paths: (1->0->0)=4, (1->0->1)=5, (1->1->0)=6, (1->1->1)=7. Sum: 4+5+6+7=22
example_2.py β€” Python
$ Input: root = [0]
β€Ί Output: 0
πŸ’‘ Note: Single node tree with value 0 represents binary '0' which equals decimal 0
example_3.py β€” Python
$ Input: root = [1,1,0,1,1,0,1]
β€Ί Output: 32
πŸ’‘ Note: Multiple paths: (1->1->1)=7, (1->1->1)=7, (1->0->0)=4, (1->0->1)=5. But actual tree structure gives different paths totaling 32

Constraints

  • The number of nodes in the tree is in the range [1, 1000]
  • Node.val is either 0 or 1
  • All answers fit within a 32-bit integer
  • Tree height will not exceed 103 levels

Visualization

Tap to expand
1Start: 0*2+1=101*2+0=211*2+1=302*2+0=412*2+1=5LeftRightProcessFinal ResultsPath 1β†’0β†’0: 4Path 1β†’0β†’1: 5Path 1β†’1: 3Sum: 4+5+3=12
Understanding the Visualization
1
Start Journey
Begin at root with accumulated value = 0
2
Build Route Code
At each node, double current value and add node's bit: value = value * 2 + bit
3
Reach Destination
When reaching a leaf (destination), record the final route code
4
Sum All Routes
Add up all unique route codes to get the final answer
Key Takeaway
🎯 Key Insight: Binary-to-decimal conversion can be done incrementally during tree traversal using bit shifting: `value = value * 2 + bit`
Asked in
Amazon 45 Microsoft 35 Google 30 Meta 20
95.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen