Sum Root to Leaf Numbers is an interesting problem from LeetCode. The problem is of medium difficulty and is about binary trees. This post is an explained solution to the problem.

I assume that you’re familiar with Python and the concept of binary trees. If you’re not, you can read this article to get started.

Image for post

The Problem

Given a binary tree whose nodes contain values 0-9, we have to find the sum of all numbers formed by root-to-leaf paths. A leaf is a node that doesn’t have any child nodes. In a binary tree, a root-to-leaf path is always unique. Here below is the expected behavior of the solution required:

Image for post

In the tree on the left, the output is 2525 is the sum of 12 and 13, which are the two numbers formed when starting from 1 and visiting every leaf. In the tree on the right, the output is 1026 as it is the sum of the three numbers 495491 and 40.

The Observations and Insights

  1. To construct a number, we traverse the tree from the root to the leaf, appending digits where the most significant digit is at the root, and the least significant digit is at the leaf. We visit some leaves before other nodes that are closer to the root. This suggests that a depth-first search will be useful.
  2. The construction of numbers is incremental and similar of sorts: the only difference between 495 and 491 (from the tree on the right) is the last digit. If we remove the 5 and insert a 1 in its place, we have the next required number. A number essentially comprises of the leaf’s digit appended to all the digits in ancestor nodes. Thus, numbers within the same subtree have common digits.
  3. Finally, notice that this problem involves a tree, so a recursive solution is helpful.

#python #linkedin #algorithms #data-structures #leetcode

Summing Root To Leaf Numbers
1.15 GEEK