If the depth of a tree is smaller than 5, the tree can be represented by an array of three-digit integers. You are given an ascending array nums of three-digit integers that represents a binary tree with depth smaller than 5. For each integer:
-
The hundreds digit is the depth
d
of the node, where
1 <= d <= 4
.
-
The tens digit is the position
p
of the node within its level, where
1 <= p <= 8
, counted as its position in a full binary tree.
-
The units digit is the value
v
of the node, where
0 <= v <= 9
.
Return the sum of all root-to-leaf path sums: for every path from the root down to a leaf, add up the node values on that path, then add those path totals together.
It is guaranteed that the array represents a valid connected binary tree.
Function Signature
def path_sum(nums: list[int]) -> int:
Rules
-
The root is at depth 1, position 1.
-
Positions within a level are numbered from 1, left to right, as if the level were completely filled. A missing node still uses up its position.
-
A leaf is a node with no children in
nums
.
-
A node that lies on several root-to-leaf paths counts once for each of those paths.
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.
Examples
Input: nums = [113, 215, 221]
Output: 12
The root has value 3, with a left child of value 5 and a right child of value 1. The two root-to-leaf paths sum to 3 + 5 = 8 and 3 + 1 = 4, and 8 + 4 = 12.
Input: nums = [113, 221]
Output: 4
The only depth-2 node is at position 2, so it is the root's right child. There is one path, 3 + 1 = 4.
Input: nums = [113, 215, 221, 314, 342]
Output: 18
Node 314 (value 4) is the left child of 215, and node 342 (value 2) sits at position 4 of depth 3, the right child of 221. The paths are 3 + 5 + 4 = 12 and 3 + 1 + 2 = 6, for a total of 18.