Problem
If the depth of a tree is smaller than 5
, then this tree can be represented by an array of three-digit integers. For each integer in this array:
- The hundreds digit represents the depth
d
of this node where1 <= d <= 4
. - The tens digit represents the position
p
of this node in the level it belongs to where1 <= p <= 8
. The position is the same as that in a full binary tree. - The units digit represents the value
v
of this node where0 <= v <= 9
.
Given an array of ascending three-digit integers nums
representing a binary tree with a depth smaller than 5
, 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.
Examples
Example 1
graph TD; C(3) --- E(5) & A(1)
|
|
Example 2
graph TD; C(3) ~~~ N1:::hidden C --- A(1) classDef hidden display:none
|
|
Solution
The problem involves calculating the sum of all root-to-leaf paths in a binary tree represented by an array of three-digit integers. Here’s how the representation works:
- The hundreds digit represents the level (depth
d
) of the node. - The tens digit represents the position (
p
) of the node within its level in a full binary tree. - The units digit represents the value of the node.
The goal is to simulate the tree traversal and compute the sum of all root-leaf paths.
Method 1 - DFS
Here is the approach:
- Parsing the array:
- Map each node to its depth, position, and value.
- Recursive DFS:
- Treat the nodes as a tree and traverse using DFS. A node is root of a subtree if it has associated child nodes.
- During traversal, compute the sum of each path by accumulating values along the way.
- Add to the total sum when a leaf node is reached (no dependent child nodes).
- Tree node recognition:
- Children of a node at
depth = d
andposition = p
are atdepth = d + 1
andpositions = 2 * p - 1
(left child) and2 * p
(right child).
- Children of a node at
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the size of the input array since each node is visited once. - 🧺 Space complexity:
O(h)
whereh
is the height of the tree (max depth 4) due to the recursion stack.