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.
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:
In the tree on the left, the output is 25
. 25
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 495
, 491
and 40
.
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.#python #linkedin #algorithms #data-structures #leetcode