Sum of Path Numbers (medium)

Problem Statement #

Given a binary tree where each node can only have a digit (0-9) value, each root-to-leaf path will represent a number. Find the total sum of all the numbers represented by all paths.

Created with Fabric.js 1.6.0-rc.1 Example 1: Output: 408 Explaination: The sume of all path numbers: 17 + 192 + 199 1 7 9 2 9
Created with Fabric.js 1.6.0-rc.1 Example 2: 1 0 1 1 6 5 Output: 332 Explaination: The sume of all path numbers: 101 + 116 + 115

Try it yourself #

Try solving this question here:

Output

3.210s

Total Sum of Path Numbers: -1

Solution #

This problem follows the Binary Tree Path Sum pattern. We can follow the same DFS approach. The additional thing we need to do is to keep track of the number representing the current path.

How do we calculate the path number for a node? Taking the first example mentioned above, say we are at node ‘7’. As we know, the path number for this node is ‘17’, which was calculated by: 1 * 10 + 7 => 17. We will follow the same approach to calculate the path number of each node.

Code #

Here is what our algorithm will look like:

Output

1.769s

Total Sum of Path Numbers: 332

Time complexity #

The time complexity of the above algorithm is O(N)O(N), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space complexity #

The space complexity of the above algorithm will be O(N)O(N) in the worst case. This space will be used to store the recursion stack. The worst case will happen when the given tree is a linked list (i.e., every node has only one child).

Mark as Completed
←    Back
All Paths for a Sum (medium)
Next    →
Path With Given Sequence (medium)