1719. 重构一棵树的方案数
难度困难
给你一个数组 pairs ,其中 pairs[i] = [x_i, y_i] ,并且满足:
-
pairs中没有重复元素 x_i < y_i
令 ways 为满足下面条件的有根树的方案数:
- 树所包含的所有节点值都在
pairs中。 - 一个数对
[x_i, y_i]出现在pairs中 当且仅当x_i是y_i的祖先或者y_i</sub>是x_i的祖先。 - 注意:构造出来的树不一定是二叉树。
两棵树被视为不同的方案当存在至少一个节点在两棵树中有不同的父节点。
请你返回:
- 如果
ways == 0,返回0。 - 如果
ways == 1,返回1。 - 如果
ways > 1,返回2。
一棵 有根树 指的是只有一个根节点的树,所有边都是从根往外的方向。
我们称从根到一个节点路径上的任意一个节点(除去节点本身)都是该节点的 祖先 。根节点没有祖先。

image.png

image.png
官方题解
太难了,,,,直接贴官方题解了。。。
class Solution:
def checkWays(self, pairs: List[List[int]]) -> int:
adj = defaultdict(set)
for x, y in pairs:
adj[x].add(y)
adj[y].add(x)
# 检测是否存在根节点
root = next((node for node, neighbours in adj.items() if len(neighbours) == len(adj) - 1), -1)
if root == -1:
return 0
ans = 1
for node, neighbours in adj.items():
if node == root:
continue
currDegree = len(neighbours)
parent = -1
parentDegree = maxsize
# 根据 degree 的大小找到 node 的父节点 parent
for neighbour in neighbours:
if currDegree <= len(adj[neighbour]) < parentDegree:
parent = neighbour
parentDegree = len(adj[neighbour])
# 检测 neighbours 是否为 adj[parent] 的子集
if parent == -1 or any(neighbour != parent and neighbour not in adj[parent] for neighbour in neighbours):
return 0
if parentDegree == currDegree:
ans = 2
return ans
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/number-of-ways-to-reconstruct-a-tree/solution/zhong-gou-yi-ke-shu-de-fang-an-shu-by-le-36e1/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。