#1719

Number Of Ways To Reconstruct A Tree

Hard
ArrayHash TableTreeGraph TheorySimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the properties of trees and ancestor relationships to efficiently determine the number of valid trees without generating all permutations. We focus on finding the root and ensuring the ancestor conditions are met.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of pairs for each node and track the potential root candidates.
  2. 2Step 2: Identify the root node, which should have exactly one parent and be involved in all pairs.
  3. 3Step 3: Check the ancestor conditions and count the valid configurations.
solution.py25 lines
1# Full working Python code
2from collections import defaultdict
3
4def count_trees(pairs):
5    indegree = defaultdict(int)
6    outdegree = defaultdict(int)
7    nodes = set()
8
9    for x, y in pairs:
10        outdegree[x] += 1
11        indegree[y] += 1
12        nodes.add(x)
13        nodes.add(y)
14
15    root_candidates = [node for node in nodes if indegree[node] == 0]
16    if len(root_candidates) != 1:
17        return 0
18
19    root = root_candidates[0]
20    ways = 1
21    for node in nodes:
22        if node != root:
23            ways *= (outdegree[node] + 1)
24    return 1 if ways == 1 else 2
25

Complexity note: The time complexity is O(n) because we only iterate through the pairs a couple of times to build our indegree and outdegree maps, making it efficient for large inputs.

  • 1The root node must be present in all pairs and have no incoming edges.
  • 2The number of valid trees can be calculated based on the outdegree of nodes.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.