Assemble a Binary Tree from Parent-Child Edge Records
Trees & GraphsModel answerLast 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]:
parentis the value of the parent node.childis the value of the child node.sideis1if the child sits on the left, or0if 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^41 <= parent, child <= 10^5sideis exactly0or1.- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem breaks down into two independent sub-tasks: materializing each node exactly once, and identifying which node is the root. Both can be solved with a single pass plus one lookup.
Core observations
Node identity via a hash map. A value like 20 can appear as a child in one record and as a parent in several others. If you naively create a new TreeNode every time you see a value, you end up with disconnected copies instead of a single connected tree. A dictionary mapping value → TreeNode solves this: create the node on first encounter, and reuse it on every subsequent reference.
Root detection via a child set. In any rooted tree with n nodes there are exactly n − 1 edges, and every non-root node is the child endpoint of exactly one edge. The root alone never appears as a child. So the root is whichever parent value is absent from the set of all child values.
Algorithm
- Initialize an empty dict
nodesand an empty setchild_values. - For each
[parent, child, side]:- Get or create
nodes[parent]andnodes[child]. - Attach
nodes[child]as the left or right child ofnodes[parent]depending onside. - Add
childtochild_values.
- Get or create
- Scan the parent value from each record; return
nodes[parent]for the first one not inchild_values.
Order of records doesn't matter because nodes are created lazily and links are just pointer assignments.
Complexity
- Time: O(m), where m = number of records. Each record does O(1) average-case dict and set operations, and the root scan is one more O(m) pass.
- Space: O(m) for the dict and the set. The output tree itself is O(n) = O(m + 1).
Python solution
from typing import List, Optional
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]]) -> Optional[TreeNode]:
nodes: dict[int, TreeNode] = {}
child_values: set[int] = set()
for parent_val, child_val, side in records:
# Get or create both endpoints.
if parent_val not in nodes:
nodes[parent_val] = TreeNode(parent_val)
if child_val not in nodes:
nodes[child_val] = TreeNode(child_val)
# Wire the edge.
if side == 1:
nodes[parent_val].left = nodes[child_val]
else:
nodes[parent_val].right = nodes[child_val]
child_values.add(child_val)
# The root is the unique parent that was never someone else's child.
for parent_val, _, _ in records:
if parent_val not in child_values:
return nodes[parent_val]
return None # Unreachable on valid input.
Walkthrough — Example 1: [[20,15,1],[20,17,0],[50,20,1],[50,80,0]]
After the main loop, child_values = {15, 17, 20, 80}. Scanning parent values: 20 is in the set, 20 again, 50 is not → return nodes[50]. The linked structure: 50.left = 20, 50.right = 80, 20.left = 15, 20.right = 17.
Common mistakes
- Creating a fresh node per row. This is the single most common bug. If you write
nodes[parent] = TreeNode(parent)unconditionally, the node built during an early "child" record gets overwritten when the same value later appears as a parent, destroying its children. - Assuming the first record's parent is the root. Records can arrive in any order;
50 → 20might appear after20 → 15. - Treating
side == 0as "no child." It means right child, not absent child. - Using recursion to build or traverse the tree. With up to 10^4 nodes in a chain (skewed tree), a recursive approach will hit Python's default ~1 000 frame recursion limit. Keep the construction iterative, as this solution does.
Trade-offs and follow-ups
Saving memory when values are densely packed. If node values were bounded by a small constant K, you could replace the dict with a plain list of length K + 1 and the set with a bytearray of length K + 1. Lookup becomes O(1) with no hashing overhead and much lower per-entry memory cost. At the given constraint (values up to 10^5, up to 10^4 records), the sparse dict is the right default.
Validating a potentially invalid input. The problem guarantees a valid tree, but if you needed to detect corruption: (a) reject any record that tries to assign a node's left or right slot a second time — that means a node has two parents; (b) after construction, BFS from the root and count visited nodes — if visited < len(nodes), a cycle exists in an unreachable component. Both checks stay O(m).
Datasets too large to fit in memory. Stream the records and use an external sort or hash-partition to find the anti-join (parents not in children) without loading everything at once. Node objects would be materialized only for the subtree currently being processed, with the rest kept on disk as an edge list.