The problem. Every node of a binary tree holds a 0 or a 1. Each root-to-leaf path spells a binary number, with the root as the most significant bit. Return the sum of all these numbers. (The answer fits in a 32-bit integer.)
Input: root = [1, 0, 1, 0, 1, 0, 1]
Output: 22 (100 + 101 + 110 + 111 in binary = 4 + 5 + 6 + 7)
Input: root = [0] Output: 0Reading a binary number left to right works like this: start at 0, and for each new bit, double the number and add the bit. 1 → 1, 10 → 2, 101 → 5. Walking down a path reads its bits in exactly that order.
Free account
Sign up to read the rest of this lesson: 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come