In LeetCode 1022. Sum of Root To Leaf Binary Numbers, you are given a binary tree where every node contains either 0 or 1. Each root-to-leaf path forms a binary number when you read the node values from the root (most significant bit) to the leaf (least significant bit). Your task is to return the sum of all these binary numbers in decimal.
Key idea
Instead of building strings like "1011" for every path, you can build the number efficiently while traversing the tree.
When you move from a node to its child, you are appending one binary digit to the end of the current number:
- Shift left by 1 (multiply by 2)
- Add the new bit (0 or 1)
So, if the current value is curr and the new node bit is node.val, then:
curr = (curr << 1) | node.val
This single line is the core of the solution.
Strategy
Use DFS (Depth-First Search) and carry the running binary value down the recursion:
- Start at the root with
curr = 0 - Update
currat every node using shifting and OR - When you reach a leaf, that
currrepresents one complete root-to-leaf binary number - Return the sum of all leaf values
Time and space complexity
- Time:
O(N)โ every node is visited once - Space:
O(H)โ recursion stack, whereHis the height of the tree
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumRootToLeaf(self, root):
def dfs(node, curr):
if not node:
return 0
# Append this bit to the running binary number
curr = (curr << 1) | node.val
# If leaf node, return the number formed by this path
if not node.left and not node.right:
return curr
# Sum from left and right subtrees
return dfs(node.left, curr) + dfs(node.right, curr)
return dfs(root, 0)
Quick example walkthrough
For a path 1 โ 0 โ 1:
- Start:
0 - After
1:(0<<1)|1 = 1(binary1) - After
0:(1<<1)|0 = 2(binary10) - After
1:(2<<1)|1 = 5(binary101)
At the leaf, add 5 to the total.