Sum all root-to-leaf path sums of a binary tree encoded as three-digit integers
Company: Alibaba
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: A binary tree of depth at most 4 is given as sorted three-digit integers that encode each node's depth, position and value. Return the total of all root-to-leaf path sums. It tests decoding an implicit tree layout, finding parents and leaves from positions, and accumulating path sums in one pass.
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.
- For each integer, the depth digit d, position digit p and value digit v satisfy 1 <= d <= 4, 1 <= p <= 8 and 0 <= v <= 9.
- It is guaranteed that nums represents a valid connected binary tree.
Examples
Input: ([117],)
Expected Output: 7
Explanation: Minimum valid: a single root is its own leaf, so the answer is its value 7.
Input: ([110],)
Expected Output: 0
Explanation: Single root 110 with value 0: one path whose sum is 0.
Hints
- Start by splitting each three-digit integer into its depth, position and value, and keep them somewhere you can ask whether a node at a given depth and position exists.
- Positions are counted as if every level were completely filled. Work out which two positions on the next level sit directly below a node at position p.
- A node is a leaf only when neither of its possible children appears in nums, so a node with exactly one child is still on the way to a leaf.