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
Number Of Ways To Reconstruct A Tree INPUT pairs array: [1, 2] [2, 3] [1, 3] Graph View: 1 2 3 Nodes: 1, 2, 3 All pairs connected ALGORITHM STEPS 1 Build Adjacency Count neighbors for nodes 2 Sort by Degree Node 1: deg=2, most 3 Find Root Root must have n-1 pairs 4 Validate Tree Check ancestor relations Degree Analysis Node Degree Role 1 2 Root 2 2 Internal 3 2 Leaf FINAL RESULT Valid Tree Found: 1 Root 2 3 Output: 1 Exactly ONE valid tree exists Key Insight: A valid tree exists iff each node's neighbors are a subset of its parent's neighbors. Root has degree n-1 (connected to all). Return 2 if nodes share same degree (multiple valid trees). Here: 1 is ancestor of both 2 and 3, and 2 is ancestor of 3 --> unique tree structure. TutorialsPoint - Number Of Ways To Reconstruct A Tree | Graph Theory Validation
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