Number Of Ways To Reconstruct A Tree - Problem
The Tree Detective Challenge
Imagine you're a detective who discovered fragments of a family tree! You have a collection of
Your mission: determine how many different valid family trees can be constructed from these clues!
๐ The Rules:
โข The tree contains exactly the people mentioned in the pairs
โข A pair
โข Each tree has exactly one root (the oldest ancestor)
โข All relationships flow from root to descendants
๐ฏ Your Task: Return
Note: Trees don't need to be binary - a person can have any number of children!
Imagine you're a detective who discovered fragments of a family tree! You have a collection of
pairs where each pair [xi, yi] tells you that two people are either ancestor-descendant or descendant-ancestor of each other in some family tree.Your mission: determine how many different valid family trees can be constructed from these clues!
๐ The Rules:
โข The tree contains exactly the people mentioned in the pairs
โข A pair
[xi, yi] exists if and only if one person is an ancestor of the otherโข Each tree has exactly one root (the oldest ancestor)
โข All relationships flow from root to descendants
๐ฏ Your Task: Return
0 if impossible, 1 if exactly one tree exists, or 2 if multiple trees are possible.Note: Trees don't need to be binary - a person can have any number of children!
Input & Output
example_1.py โ Basic Tree
$
Input:
pairs = [[1,2],[2,3],[1,3]]
โบ
Output:
2
๐ก Note:
Multiple trees possible: Root can be 1 (with 2,3 as children and 2โ3) or root can be 2 (with 1,3 as children). Both form valid trees with the given ancestor relationships.
example_2.py โ Unique Tree
$
Input:
pairs = [[1,2],[2,3],[2,4]]
โบ
Output:
1
๐ก Note:
Only one tree structure possible: 2 must be the root (highest degree), with 1, 3, 4 as its children. Any other root arrangement would violate the pair constraints.
Constraints
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code