Validate Binary Tree from Directed Edge List
Trees & GraphsAuto-graded · 24 test casesLast updated
Evaluates tree properties, cycle detection, edge validity, and in-order traversal under strict error precedence.
Given a list of directed edges [parent, child] using positive integer node identifiers, determine if the graph forms a single valid binary tree. The set of nodes in the graph is defined as all unique node IDs appearing in the input edge list.
A valid binary tree satisfies all of the following conditions:
- There is exactly one root node (a node with no incoming parent edges).
- Every non-root node has exactly one parent node.
- No node has more than two child nodes.
- The graph contains no cycles and is fully connected (all nodes are reachable from the single root node).
Left/Right Child Ordering Rules
The edges appear in a given fixed order:
- The first directed edge originating from a parent node points to its left child.
- The second directed edge originating from a parent node points to its right child.
- If a parent node has only one child edge, that child is treated as its left child.
Verification Priority Rules
If the graph fails to form a single valid binary tree, you must identify and return the first applicable error code from the following ordered hierarchy:
INVALID_INPUT— An edge is a self-loop (whereparent == child) OR an exact identical directed edge[parent, child]appears multiple times.TOO_MANY_CHILDREN— A parent node has more than two child edges.MULTIPLE_PARENTS— A child node has more than one parent edge.CYCLE— The graph contains at least one directed cycle.MULTIPLE_ROOTS— There are two or more nodes that have no incoming parent edges (a forest of disjoint components).
If all checks pass and the edges form a valid binary tree, output the node values as a space-separated string corresponding to the tree's in-order traversal (left subtree, current node, right subtree).
Input Format
edges: A list of 2-element integer lists[parent, child].
Output Format
- Return a single string: either the exact error string (e.g.,
"CYCLE") or space-separated node labels representing the in-order traversal (e.g.,"4 2 1 5 3").
Constraints
1 <= len(edges) <= 10^41 <= node label <= 10^5- Input errors at higher priority must be reported even if lower-priority errors exist further along in processing.
Examples
Example 1
Input: validate_binary_tree([[1, 2], [1, 3], [2, 4], [3, 5]])
Output: '4 2 1 5 3'
Example 2
Input: validate_binary_tree([[1, 2], [2, 3], [3, 1]])
Output: 'CYCLE'
Example 3
Input: validate_binary_tree([[1, 2], [1, 3], [1, 4]])
Output: 'TOO_MANY_CHILDREN'
Example 4
Input: validate_binary_tree([[1, 2], [3, 4]])
Output: 'MULTIPLE_ROOTS'
Example 5
Input: validate_binary_tree([[1, 2], [1, 2]])
Output: 'INVALID_INPUT'
Example 6
Input: validate_binary_tree([[1, 2], [1, 3], [2, 4], [3, 4]])
Output: 'MULTIPLE_PARENTS'
Hints
Hint 1
Strictly follow the error hierarchy: perform checks sequentially from step 1 to step 5.
Hint 2
When recording children for a parent node, maintain the original sequence of edges to preserve left and right subtree assignments.
Hint 3
Use a 3-color state iterative DFS (0=unvisited, 1=visiting, 2=visited) to safely detect directed cycles without stack overflow.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires validating graph structures against specific binary tree rules and prioritizing error reporting. To resolve this correctly, we process validation checks sequentially in the exact specified priority order:
-
Input Integrity (
INVALID_INPUT): We iterate through all given edges. If any edge connects a node to itself (parent == child) or if an edge(parent, child)has been encountered previously, we return"INVALID_INPUT"immediately. Simultaneously, we construct adjacency maps for parents, children, and a master set of all unique nodes. -
Parent Out-Degree (
TOO_MANY_CHILDREN): We inspect the adjacency map of children. If any parent node has strictly more than 2 children, we return"TOO_MANY_CHILDREN". -
Child In-Degree (
MULTIPLE_PARENTS): We inspect the parent mappings. If any node is pointed to by more than 1 parent node, we return"MULTIPLE_PARENTS". -
Cycle Detection (
CYCLE): We use an iterative three-color Depth-First Search (DFS) algorithm across all graph nodes:- State
0(Unvisited) - State
1(Visiting / on current traversal path) - State
2(Visited / fully explored) Reaching a neighbor with state1indicates a back-edge (a directed cycle), returning"CYCLE". Using an explicit stack avoids recursion limit issues on large linear graphs.
- State
-
Root Node Validation (
MULTIPLE_ROOTS): Nodes that do not appear as children in any edge are candidate root nodes. If there are multiple root nodes, the graph is a forest of disconnected components, so we return"MULTIPLE_ROOTS". -
In-Order Traversal: Once validated, we start at the single root node and execute an iterative in-order traversal using an explicit stack:
- Go as far left as possible (the first edge listed for a parent).
- Pop and append the node label to our output sequence.
- Proceed to the right child (the second edge listed for a parent, if present).
Complexity Analysis
- Time Complexity: $\mathcal{O}(E)$, where $E$ is the number of edges. Each edge is processed a constant number of times during map construction, degree checks, DFS traversal, and final tree traversal.
- Space Complexity: $\mathcal{O}(E + V)$, where $V \le E + 1$ is the number of unique node labels. Storage is required for adjacency mappings, node states, and traversal stacks.
from typing import List
def validate_binary_tree(edges: List[List[int]]) -> str:
nodes = set()
children = {}
parents = {}
seen_edges = set()
# Priority 1: Check for self-loops and duplicate edges across ALL edges first
for parent, child in edges:
if parent == child or (parent, child) in seen_edges:
return "INVALID_INPUT"
seen_edges.add((parent, child))
nodes.add(parent)
nodes.add(child)
children.setdefault(parent, []).append(child)
parents.setdefault(child, []).append(parent)
# Priority 2: Check max out-degree
if any(len(child_list) > 2 for child_list in children.values()):
return "TOO_MANY_CHILDREN"
# Priority 3: Check max in-degree
if any(len(parent_list) > 1 for parent_list in parents.values()):
return "MULTIPLE_PARENTS"
# Priority 4: Cycle detection via 3-color iterative DFS
# 0 = white (unvisited), 1 = gray (on stack), 2 = black (completed)
state = {}
for start in nodes:
if state.get(start, 0) != 0:
continue
state[start] = 1
stack = [(start, 0)]
while stack:
node, index = stack[-1]
child_list = children.get(node, [])
if index == len(child_list):
state[node] = 2
stack.pop()
continue
child = child_list[index]
stack[-1] = (node, index + 1)
child_state = state.get(child, 0)
if child_state == 1:
return "CYCLE"
if child_state == 0:
state[child] = 1
stack.append((child, 0))
# Priority 5: Root count validation
roots = [node for node in nodes if node not in parents]
if len(roots) > 1:
return "MULTIPLE_ROOTS"
if len(roots) == 0:
return "CYCLE"
# Perform iterative in-order traversal starting at the root
root = roots[0]
result = []
stack = []
current = root
while stack or current is not None:
while current is not None:
stack.append(current)
current = children.get(current, [None])[0]
current = stack.pop()
result.append(str(current))
child_list = children.get(current, [])
current = child_list[1] if len(child_list) == 2 else None
if len(result) != len(nodes):
return "CYCLE"
return " ".join(result)