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 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

Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen