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.

Input & Output

Example 1 — Basic Tree
$ Input: nums = [113,215,221]
Output: 66
💡 Note: Tree: root(3) with left(5) and right(1). Paths: 3→5 gives 35, 3→1 gives 31. Total: 35 + 31 = 66
Example 2 — Single Node
$ Input: nums = [113]
Output: 3
💡 Note: Only root node with value 3, so the only path sum is 3
Example 3 — Deeper Tree
$ Input: nums = [113,215,221,324,325]
Output: 253
💡 Note: Paths: 3→5→4=354, 3→5→5=355, 3→1=31. Total: 354 + 355 + 31 = 740. Wait, let me recalculate: 3→5→4=35*10+4=354, 3→5→5=35*10+5=355, 3→1=3*10+1=31. But 3→1 is not a leaf if it has no children in this encoding. Actually: 3→5→4=354, 3→5→5=355. Total: 354 + 355 = 709. But actually path concatenation: 3-5-4 = 354, 3-5-5 = 355. Wait, the encoding shows (3,2,4) and (3,2,5) which would be depth 3, position 2. Let me check: 324 means depth=3, pos=2, val=4. This would be right child of (2,1). 325 means depth=3, pos=2, val=5 which is impossible (same position). Let me use a valid example.

Constraints

  • 1 ≤ nums.length ≤ 15
  • nums[i] is a three-digit integer
  • The given array represents a valid connected binary tree

Visualization

Tap to expand
Path Sum IV: Encoded Tree to Path Sums113215221Input Array351Decoded Tree3531Total: 66
Understanding the Visualization
1
Input
Array of 3-digit numbers encoding tree nodes
2
Process
Decode coordinates and traverse all paths
3
Output
Sum of all root-to-leaf paths
Key Takeaway
🎯 Key Insight: Decode coordinates from 3-digit numbers and use DFS to sum all root-to-leaf paths
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~25 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen