KatInterview

Assemble a Binary Tree from Parent-Child Edge Records

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbinary-treehash-maptree-construction

Last updated

Given a list of directed labeled edges, reconstruct the binary tree they describe and return its root node.

Problem

You receive a list of records, where each record describes one edge in a binary tree. Record i has the form [parent, child, side]:

  • parent is the value of the parent node.
  • child is the value of the child node.
  • side is 1 if the child sits on the left, or 0 if it sits on the right.

Using these records, build the binary tree and return its root node. The input is guaranteed to be consistent: no cycles, no node with two parents, and exactly one root.

Function Signature

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def buildTreeFromEdges(records: list[list[int]]) -> TreeNode:

Examples

Example 1

Input:  [[20,15,1],[20,17,0],[50,20,1],[50,80,0]]

Expected tree:

        50
       /  \
      20   80
     /  \
    15   17

Return the node with value 50.

Example 2

Input:  [[1,2,1],[2,3,0],[3,4,1]]

Expected tree:

1
 \
  (no right)
 /
2
 \
  3
 /
4

More precisely: 1 → left → 2 → right → 3 → left → 4. Return the node with value 1.

Constraints

  • 1 <= records.length <= 10^4
  • 1 <= parent, child <= 10^5
  • side is exactly 0 or 1.
  • The described tree is valid and has a unique root.

What to return

Return the TreeNode object that is the root of the constructed tree (the node that has no parent).

Edge cases to consider

  • A highly skewed tree where every node has only one child (a chain of length up to 10^4).
  • Records that arrive in an order that mentions a child before that same value later appears as a parent.
  • Identifying the root correctly when many different values all appear as parents.

Hints

Hint 1

The root is the only node value that shows up as a parent but never as a child. Keep a set of every value that appears in the child position as you scan the records.

Hint 2

A single value can appear in multiple records — once as a child, and again as a parent. Use a dictionary keyed by value so you create each TreeNode exactly once and every reference to that value points to the same object.

Hint 3

You don't need the records to be in any particular order. Build all nodes and wire all edges in one pass, then do a second pass to find which parent value is absent from your child set.