Path Sum IV - 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
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.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code