> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Path Sum IV Python Solution with Tests

> Tested Python solution for LeetCode 666 with 17 pytest cases. Generate a practice environment with lcpy.

LeetCode 666, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/path-sum-iv/description/).

Generate this problem as a practice environment: tested reference solution, 17 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 666   # by problem number
lcpy gen -s path_sum_iv   # by problem name
```

## Problem

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 `d` of this node, where `1 <= d <= 4`.
* The tens digit represents the position `p` of this node within its level, where `1 <= p <= 8`, corresponding to its position in a **full binary tree**.
* The units digit represents the value `v` of this node, where `0 <= 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.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-1-tree.jpg)

```
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](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0666.Path%20Sum%20IV/images/pathsum4-2-tree.jpg)

```
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 \<= 15
* 110 \<= nums\[i] \<= 489
* nums represents a valid binary tree with depth less than 5.
* nums is sorted in ascending order.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/path_sum_iv/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/path_sum_iv/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n) where n = len(nums); each node is visited once
    # Space: O(n) for the node lookup map plus O(depth) recursion
    def path_sum(self, nums: list[int]) -> int:
        # Node key is depth * 10 + position; value is the units digit
        nodes = {num // 10: num % 10 for num in nums}
        total = 0
        stack: list[tuple[int, int]] = [(11, 0)]
        while stack:
            node, running = stack.pop()
            if node not in nodes:
                continue
            running += nodes[node]
            depth, pos = divmod(node, 10)
            left = (depth + 1) * 10 + pos * 2 - 1
            right = left + 1
            if left in nodes or right in nodes:
                stack.append((left, running))
                stack.append((right, running))
            else:
                total += running
        return total
```

## Complexity

| Time | Space |
| - | - |
| O(n) where n = len(nums); each node is visited once | O(n) for the node lookup map plus O(depth) recursion |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.