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.
class Solution: # Time: O(n) where n = len(nums); each node is visited once # Space: O(n) for the node lookup map plus O(depth) recursion def path_sum(self, nums: list[int]) -> int: # Node key is depth * 10 + position; value is the units digit nodes = {num // 10: num % 10 for num in nums} total = 0 stack: list[tuple[int, int]] = [(11, 0)] while stack: node, running = stack.pop() if node not in nodes: continue running += nodes[node] depth, pos = divmod(node, 10) left = (depth + 1) * 10 + pos * 2 - 1 right = left + 1 if left in nodes or right in nodes: stack.append((left, running)) stack.append((right, running)) else: total += running return total