FunctionRacerProblemsRace

Sum of Root-to-Leaf Binary Numbers

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Every node holds 0 or 1. Reading the values along a root-to-leaf path from the top gives a binary number (the path 1 -> 0 -> 1 is 101, which is 5). Return the sum of these numbers over all root-to-leaf paths, as a normal integer. An empty tree gives 0.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [1,0,1,0,1,0,1]
returns 22

100 + 101 + 110 + 111 = 4 + 5 + 6 + 7 = 22.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems