KatInterview

Assemble Tree from Edge Specifications

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstreeshash-tablegraph-construction

Last 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_val is the value of the parent node
  • child_val is the value of the child node
  • direction is 1 if the child is a left child, or 0 if 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.