Problem Description
Given an ascending array of three-digit integers where each integer represents a node in a binary tree, decode the tree structure and return the sum of all the path sums from the root to each leaf. The hundreds digit represents the depth (1 <= d <= 4), the tens digit represents the position within the level (following the full binary tree indexing), and the units digit represents the node's value.
Key Insights
- The encoded integer has three parts: depth, position, and value.
- The tree is represented implicitly; using the depth and position, compute the keys for left and right children.
- Use a dictionary (or map) to store nodes for constant time lookup.
- Use depth-first search (DFS) to traverse from the root to each leaf, maintaining a running sum.
- When a leaf node is reached, add its path sum to the total result.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes (at most 15), since each node is visited once. Space Complexity: O(N) for the recursion stack and node map storage.
Solution
We convert each three-digit number into a key formed by depth * 10 + position and store its value in a dictionary. The left child of a node at (d, p) is at (d+1, 2p-1) and the right child is at (d+1, 2p). Using DFS, we start at the root (key 11) and traverse the tree, accumulating the path sum until we reach a leaf (a node without any children). The sum of all root-to-leaf path sums is then computed.