Validate a Binary Tree Built from Directed Edges
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
You are given a list of directed edges. Each edge is a pair (parent, child) of positive-integer node labels, meaning parent points to child. The set of nodes is exactly the set of labels that appear in at least one edge.
Determine whether the edges form a single valid binary tree:
If the edges do not form a valid binary tree, output the first error code that applies from the priority list below (check in this exact order and report only the highest-priority error):
INVALID_INPUT
— some edge is a self-loop (
parent == child
), or the exact same
(parent, child)
edge appears more than once.
TOO_MANY_CHILDREN
— some node appears as the parent in more than two edges.
MULTIPLE_PARENTS
— some node appears as the child in more than one edge.
CYCLE
— the edges contain a directed cycle.
MULTIPLE_ROOTS
— more than one node has no parent (the edges form a forest of two or more trees).
If the edges do form a valid binary tree, output its in-order traversal serialization: visit the left subtree, then the node, then the right subtree, and print the node labels separated by single spaces.
Edges are given in a fixed order. For any parent node:
edges
: a list of pairs
[parent, child]
of positive integers, in a fixed given order.
Return a single string:
Example 1 — valid tree
edges = [[1,2],[1,3],[2,4],[3,5]]
Node 1 has left child 2 and right child 3; node 2 has left child 4; node 3 has left child 5.
Output: 4 2 1 5 3
Example 2 — cycle
edges = [[1,2],[2,3],[3,1]]
Every node has exactly one parent and at most two children, but the edges form a directed cycle.
Output: CYCLE
Example 3 — too many children
edges = [[1,2],[1,3],[1,4]]
Node 1 has three children.
Output: TOO_MANY_CHILDREN
Example 4 — multiple roots
edges = [[1,2],[3,4]]
Nodes 1 and 3 both have no parent, so the edges form a forest.
Output: MULTIPLE_ROOTS
Example 5 — duplicate edge
edges = [[1,2],[1,2]]
The edge (1,2) appears twice.
Output: INVALID_INPUT
Example 6 — multiple parents
edges = [[1,2],[1,3],[2,4],[3,4]]
Node 4 has two parents (2 and 3).
Output: MULTIPLE_PARENTS
1 <= number of edges <= 10^4
1 <= node label <= 10^5