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
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`
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code