#1022

Sum of Root To Leaf Binary Numbers

newbie · 210 · lc easy +16 · verified · 76.6% accepted · 3,778 likes · top 88%

Description

In a binary tree where every node stores 0 or 1, each root-to-leaf path encodes a binary number (most-significant bit first).

- For example, the path 0 -> 1 -> 1 -> 0 -> 1 encodes 01101 in binary, which equals 13.

Return the sum of all binary numbers represented by root-to-leaf paths. The answer is guaranteed to fit in a 32-bit integer.

Example 1:

Input: root = [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Example 2:

Input: root = [0]
Output: 0

Code

1
2
3
4
5
6
7
8
9