666. Path Sum IV π
Description
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.
Solutions
Solution 1
Thinking
Nodes are encoded as depth, position, and value. Building an explicit tree is unnecessary.
Map \(depth\times 10+pos\) to the value. DFS from \(11\) using the child-index formula; when both children are missing, add the path sum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |

