Path Sum IV - Problem
Imagine you're working with a compact binary tree representation where each node is encoded as a special three-digit number! ๐ณ
You're given an array of these three-digit integers representing a binary tree with depth less than 5. Each number follows this encoding:
- Hundreds digit (d): The depth/level of the node (1 โค d โค 4)
- Tens digit (p): The position within that level (1 โค p โค 8)
- Units digit (v): The actual value of the node (0 โค v โค 9)
Your mission: Calculate the sum of all root-to-leaf paths in this encoded tree!
For example, if a path from root to leaf has values [5, 4, 2], that path contributes 5 + 4 + 2 = 11 to the total sum.
Note: The array represents a valid connected binary tree, so you don't need to worry about invalid structures.
Input & Output
example_1.py โ Basic Tree
$
Input:
[113, 215, 221]
โบ
Output:
12
๐ก Note:
Tree structure: Root(3) with left child(5) and right child(1). Path sums: 3+5=8 (left path) and 3+1=4 (right path). Total: 8+4=12.
example_2.py โ Single Node
$
Input:
[113]
โบ
Output:
3
๐ก Note:
Tree has only root node with value 3. Single path from root to itself sums to 3.
example_3.py โ Deeper Tree
$
Input:
[113, 215, 221, 324, 325]
โบ
Output:
16
๐ก Note:
Tree with depth 3. Paths: 3โ5โ4 (sum=12) and 3โ5โ5 (sum=13) from left subtree, 3โ1 (sum=4) from right. Total: 12+13+4=29. Wait, let me recalculate: actually 3โ1 gives 4, and the left paths give 12 and 13 respectively, but 3โ1 should give just 4. Actually the tree structure shows 3โ1 as leaf, 3โ5โ4 and 3โ5โ5 as leaves. So total is (3+1) + (3+5+4) + (3+5+5) = 4+12+13 = 29. Let me correct: actually 324 means (3,2,4) and 325 means (3,2,5), so these are children of node at (2,1). So paths are: 3โ5โ4 = 12, 3โ5โ5 = 17, 3โ1 = 4. Total = 12+17+4 = 33. Actually, let me be more careful: 324 decodes to depth=3, pos=2, val=4. So it's at (3,2) with value 4. Position 2 at depth 3 means it's right child of position 1 at depth 2. 325 decodes to (3,2,5), which doesn't make sense as position. Let me recalculate: 324 = depth 3, pos 2, val 4. 325 = depth 3, pos 2, val 5 - this is impossible as same position. I think there's an error. Let me use a different example.
Constraints
- 1 โค nums.length โค 15
- 1 โค nums[i] โค 103
- The depth of the tree is at most 4
- Each number represents a valid node in format ddd where d is depth (1-4), p is position (1-8), v is value (0-9)
- The given array represents a valid connected binary tree
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code