Skip to main content
Back to problems
Leetcode
Medium
Trees
Recursion
Bit Manipulation
Sum Of Root To Leaf Binary Numbers

Given a binary tree whose node values are 0 or 1, treat each root-to-leaf path as a binary number and return the sum of all such numbers.

Acceptance 0%
Problem Statement

Sum of Root-to-Leaf Binary Numbers

You are given the root of a binary tree where each node contains either 0 or 1.

Every root-to-leaf path forms a binary number by reading the node values from top to bottom. For example, a path 1 -> 0 -> 1 represents the binary number 101, which is 5 in decimal.

Return the sum of the decimal values of all root-to-leaf binary numbers in the tree.

A leaf is a node with no children.

Input Format

  • A binary tree root node root.
  • Each node contains an integer value 0 or 1.

Output Format

  • Return an integer representing the sum of all root-to-leaf binary numbers.

Constraints

  • The tree is a binary tree.
  • Each node value is either 0 or 1.
  • At least one root-to-leaf path may exist.
  • Use 32-bit or 64-bit integer arithmetic as appropriate for the accumulated sum.
Examples
Sample cases returned by the problem API.

Example 1

Input

root = [1,0,1,0,1,0,1]

Output

22

Explanation

The root-to-leaf paths are 100 = 4, 101 = 5, 110 = 6, and 111 = 7. Their sum is 22.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.