Number Of Ways To Reconstruct A Tree - Problem

You are given an array pairs, where pairs[i] = [xi, yi], and:

  • There are no duplicates.
  • xi < yi

Let ways be the number of rooted trees that satisfy the following conditions:

  • The tree consists of nodes whose values appeared in pairs.
  • A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi.
  • Note: the tree does not have to be a binary tree.

Two ways are considered to be different if there is at least one node that has different parents in both ways.

Return:

  • 0 if ways == 0
  • 1 if ways == 1
  • 2 if ways > 1

A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.

An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.

Input & Output

Example 1 — Complete Triangle
$ Input: pairs = [[1,2],[2,3],[1,3]]
Output: 1
💡 Note: All three nodes are connected to each other. There's exactly one way to form a tree: any node can be root with the other two as children, but the ancestor relationships determine a unique structure.
Example 2 — Linear Chain
$ Input: pairs = [[1,2],[2,3]]
Output: 1
💡 Note: Forms a simple path 1-2-3. There's exactly one tree structure that satisfies the ancestor relationships.
Example 3 — Impossible Structure
$ Input: pairs = [[1,2],[3,4]]
Output: 0
💡 Note: Two disconnected components cannot form a single tree. No valid tree structure exists.

Constraints

  • 1 ≤ pairs.length ≤ 500
  • 1 ≤ xi < yi ≤ 500
  • The elements in pairs are unique.

Visualization

Tap to expand
Tree Reconstruction: From Pairs to Tree CountInput Pairs[[1,2],[2,3],[1,3]]Ancestor-DescendantRelationships123Graph from PairsTree Analysisn = 3 nodesedges = 3 = completeConnected ✓123Result: 1Exactly one valid tree
Understanding the Visualization
1
Input Pairs
Given pairs represent ancestor-descendant relationships
2
Graph Analysis
Build graph and check tree properties
3
Count Trees
Determine number of valid tree structures
Key Takeaway
🎯 Key Insight: Complete graphs with specific properties can have 0, 1, or multiple valid tree decompositions
Asked in
Google 15 Microsoft 8
12.0K Views
Medium Frequency
~35 min Avg. Time
245 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