You are given a list edges where each edges[i] = [parent, child] is a directed edge from a parent node to a child node. Find the node that could be the root of a valid binary tree formed by these edges.
The edges form a valid binary tree when all of the following hold:
-
There is exactly one root node (a node with no parent).
-
Every non-root node has exactly one parent.
-
Each node has at most two children.
-
All nodes are connected, meaning every node is reachable from the root.
If a valid binary tree can be formed, return the value of its root. Otherwise return -1.
Function Signature
def find_root(edges: list[list[int]]) -> int:
Rules
-
The set of nodes is exactly the set of labels that appear in at least one edge, as a parent or as a child.
-
Every pair in
edges
counts as its own edge. If the same
[parent, child]
pair appears twice, that child has two incoming edges and the input is not a valid tree.
-
Children have no left or right order. A node with zero, one or two children is fine.
-
A valid binary tree has exactly one root, so whenever the answer is not
-1
it is unique.
Constraints
-
1 <= edges.length <= 10^4
-
0 <= edges[i][0], edges[i][1] <= 10^4
-
edges[i][0] != edges[i][1]
Examples
Input: edges = [[1,2],[1,3],[3,4],[3,5]]
Output: 1
Node 1 has no parent, nodes 2 through 5 each have exactly one parent, and nodes 1 and 3 have two children each. Every node is reachable from 1: its children are 2 and 3, and the children of 3 are 4 and 5.
Input: edges = [[1,2],[2,3],[3,1]]
Output: -1
The edges form the cycle 1 -> 2 -> 3 -> 1, so every node has a parent and there is no root.
Input: edges = [[0,1],[2,3],[3,2]]
Output: -1
Node 0 is the only node with no parent and every other node has exactly one parent, but nodes 2 and 3 form a cycle that cannot be reached from 0.