Back to course home
0% completed
Sum of Root To Leaf Binary Numbers (easy)
Problem Statement
You are given the root of a binary tree, where each node holds either a 0
or 1
. Each path from the root to a leaf forms a binary number.
For example, if the path is 1 -> 0 -> 1
, then this could represent 101 in binary, which is 5 in decimal representation. You need to consider all these root-to-leaf paths, convert them to binary numbers and sum them.
Return the total sum of all these binary numbers.
The test cases are generated so that the answer fits in a 32-bits integer.
Examples
Example 1
- Input: root =
[1,0,1,0,1,null,1]
- Expected Output:
16
- Explanation: The paths from the root to leaves represent binary numbers
100
,101
, and111
. Their decimal equivalents are 4, 5, and 7, respectively. The sum of these numbers is4 + 5 + 7 = 16
.
Example 2
- Input: root =
[1,1,0,1,1,0,1]
- Expected Output:
23
- Explanation: The paths represent binary numbers
111
,111
,100
and101
. Their decimal equivalents are 7, 5, 4, and 5, respectively. The sum is7 + 7 + 4 + 5 = 23
.
Example 3
- Input: root =
[1,0,1,null,null,0,1]
- Expected Output:
15
- Explanation: The paths represent binary numbers
10
,110
, and111
. Their decimal equivalents are 2, 6, and 7, respectively. The sum is2 + 6 + 7 = 15
.
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- Node.val is 0 or 1.
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
Mark as Completed
Table of Contents
Problem Statement
Examples
Try it yourself