Sum Root-to-Leaf Binary Numbers
Problem statement
You are given the root of a binary tree whose node values are 0 or 1.
Each root-to-leaf path represents a binary number, with the root as its most significant bit. Return the sum of all represented numbers.
A leaf is a node with no children.
Function
sumRootToLeaf(root: TreeNode) → intExamples
Example 1
root = [1,0,1,0,1,0,1]return = 22The four paths represent 100, 101, 110, and 111, which sum to 22.
Example 2
root = [0]return = 0The only path represents zero.
Example 3
root = [1]return = 1The only path represents one.
Constraints
- The tree contains between
1and1000nodes. node.valis0or1.- The sum fits a signed 32-bit integer.