Problem · Tree

Sum Root-to-Leaf Numbers

Learn this problem
MediumMeta logoMetaFULLTIMEONSITE INTERVIEW
See Meta hiring insights

Problem statement

You are given the root of a binary tree. Every node stores one decimal digit from 0 through 9. Each root-to-leaf path represents the number formed by reading its digits from root to leaf.

Return the sum of the numbers represented by all root-to-leaf paths. A leaf has no children. Return 0 for an empty tree.

Follow-up

How can an iterative traversal avoid call-stack overflow on a very deep tree?

Function

sumNumbers(root: TreeNode) → int

Examples

Example 1

root = [1,2,3]return = 25

The paths form 12 and 13, whose sum is 25.

Example 2

root = [4,9,0,5,1]return = 1026

The paths form 495, 491, and 40.

Example 3

root = []return = 0

An empty tree has no root-to-leaf paths.

Constraints

  • Each node value is between 0 and 9.
  • The tree may be empty.
  • The final sum fits in a signed 32-bit integer.

More Meta problems

drafts saved locally
public int sumNumbers(TreeNode root) {
    // Write your code here.
}
root[1,2,3]
expected25
checking account