Path Sum IV Problem
Description
LeetCode Problem 666.
If the depth of a tree is smaller than 5, then this tree can be represented by an array of three-digit integers. You are given an ascending array nums consisting of three-digit integers representing a binary tree with a depth smaller than 5, where for each integer:
- The hundreds digit represents the depth
dof this node, where1 <= d <= 4. - The tens digit represents the position
pof this node within its level, where1 <= p <= 8, corresponding to its position in a full binary tree. - The units digit represents the value
vof this node, where0 <= v <= 9.
Return the sum of all paths from the root towards the leaves.
It is guaranteed that the given array represents a valid connected binary tree.
Example 1:

Input: nums = [113,215,221]
Output: 12
Explanation:
The tree that the list represents is shown.
The path sum is (3 + 5) + (3 + 1) = 12.
Example 2:

Input: nums = [113,221]
Output: 4
Explanation:
The tree that the list represents is shown.
The path sum is (3 + 1) = 4.
Constraints:
1 <= nums.length <= 15110 <= nums[i] <= 489numsrepresents a valid binary tree with depth less than5.numsis sorted in ascending order.
Solution
Approach: Hash Map and DFS
We do not need to build the tree. The first two digits of each number (depth * 10 + position) identify a node, so we store key -> value in a hash map.
Positions follow a full binary tree, so the children of the node at depth d, position p are at depth d + 1, positions 2p - 1 and 2p. Their keys are left = (d + 1) * 10 + 2p - 1 and right = left + 1.
Run a DFS from the root key 11, passing down the sum of the values on the path so far:
- Add the current node's value.
- If neither child key is in the map, the node is a leaf and its path sum counts toward the answer.
- Otherwise, recurse into the children that exist.
Be careful with nodes that have only one child: they are not leaves, so their path sum is not counted alone, and the missing child is skipped rather than treated as a leaf.
Complexity: O(n) time and O(n) extra space, with at most 15 nodes.
class Solution:
def pathSum(self, nums: List[int]) -> int:
# key = depth * 10 + position, the first two digits of each number.
value = {x // 10: x % 10 for x in nums}
def dfs(key, s):
"""Sum of all root-to-leaf paths through this node; s is the sum above it."""
s += value[key]
depth, pos = divmod(key, 10)
left = (depth + 1) * 10 + 2 * pos - 1
right = left + 1
if left not in value and right not in value:
return s # a leaf ends one path
total = 0
if left in value:
total += dfs(left, s)
if right in value:
total += dfs(right, s)
return total
return dfs(11, 0)