Assemble Tree from Edge Specifications
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests building a tree structure from unordered edge list by tracking node relationships and identifying the root.
You receive a collection of edges that describe a binary tree. Each edge is given as a triple [parent_val, child_val, direction], where:
parent_valis the value of the parent nodechild_valis the value of the child nodedirectionis1if the child is a left child, or0if the child is a right child
The edges may be provided in any order. Your task is to reconstruct the tree and return it as a serialized representation.
Output Format: Return a list of node records, where each record is [value, left_child_value, right_child_value]. Use None for missing children. Sort the records by node value in ascending order.
Key Properties:
- Each value uniquely identifies a node
- A node may be mentioned as a child before it appears as a parent
- The tree has exactly one root (a node that never appears as anyone's child)
- Each node has at most one parent and at most two children
Constraints
1 <= len(descriptions) <= 100,000- Node values are distinct signed 32-bit integers
- The input describes exactly one valid binary tree
- No node has more than one parent
- No parent has multiple children on the same side (left or right)
Examples
Example 1
Input: assemble_tree([[20, 15, 1], [20, 17, 0], [50, 20, 1], [50, 80, 0], [80, 19, 1]])
Output: [[15, None, None], [17, None, None], [19, None, None], [20, 15, 17], [50, 20, 80], [80, 19, None]]
Example 2
Input: assemble_tree([[1, 2, 1]])
Output: [[1, 2, None], [2, None, None]]
Example 3
Input: assemble_tree([[10, 5, 1], [10, 15, 0], [5, 2, 1], [5, 7, 0], [15, 12, 1], [15, 20, 0]])
Output: [[2, None, None], [5, 2, 7], [7, None, None], [10, 5, 15], [12, None, None], [15, 12, 20], [20, None, None]]
Hints
Hint 1
Track all nodes in a dictionary mapping values to their left and right children, creating entries on first appearance.
Hint 2
The root is the only node value that never appears in the child position of any edge.
Hint 3
Use depth-first traversal from the root to collect all reachable nodes, then format and sort the output.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution builds the tree in three phases:
Phase 1: Build node relationship map
Maintain a dictionary where each node value maps to a pair [left_child, right_child]. As you process each edge, ensure both parent and child have entries (initialize with [None, None] if new), then store the child in the appropriate slot (index 0 for left when direction is 1, index 1 for right when direction is 0). Also track all values that appear as children in a separate set.
Phase 2: Identify the root
In a valid tree with n nodes, there are exactly n-1 parent-child relationships. Every node except the root appears exactly once as a child. Find the single value that exists in your value collection but not in the children set—this is your root.
Phase 3: Serialize via traversal
Starting from the root, perform a depth-first traversal using an iterative stack to avoid recursion limits on deep trees. For each visited node, record its value and children as a triple. Track visited nodes to prevent revisiting. Finally, sort the output records by node value to produce a canonical ordering.
Why It Works
- Order independence: Each edge only writes to one specific slot (parent's left or right), so processing edges in any sequence produces identical results.
- Forward references: Creating a node's entry when it first appears (even as a child) means subsequent edges referencing it as a parent simply update the existing entry.
- Root detection: Since each non-root node has exactly one incoming edge, the count of children is n-1, leaving exactly one value unclaimed—the root.
- Completeness: DFS from the root in a connected tree visits every reachable node exactly once, producing the full serialization.
Complexity
Time: O(n log n) where n is the number of edges. Building the relationship map takes O(n) with hash operations. Finding the root takes O(n). The traversal takes O(n). The final sort dominates at O(n log n).
Space: O(n) for the node map, the children set, the value set, the traversal stack, and the output list.
Solution Code
from typing import List, Optional
def assemble_tree(descriptions: List[List[int]]) -> List[List[Optional[int]]]:
node_children = {}
children_set = set()
all_values = set()
for parent_val, child_val, direction in descriptions:
all_values.add(parent_val)
all_values.add(child_val)
children_set.add(child_val)
if parent_val not in node_children:
node_children[parent_val] = [None, None]
if child_val not in node_children:
node_children[child_val] = [None, None]
node_children[parent_val][0 if direction else 1] = child_val
root_val = next(val for val in all_values if val not in children_set)
output = []
traversal_stack = [root_val]
visited = set()
while traversal_stack:
current_val = traversal_stack.pop()
if current_val in visited:
continue
visited.add(current_val)
left_child, right_child = node_children[current_val]
output.append([current_val, left_child, right_child])
if right_child is not None:
traversal_stack.append(right_child)
if left_child is not None:
traversal_stack.append(left_child)
output.sort(key=lambda rec: rec[0])
return output