LeetCode 题解工作台

重构一棵树的方案数

给你一个数组 pairs ,其中 pairs[i] = [x i , y i ] ,并且满足: pairs 中没有重复元素 x i i 令 ways 为满足下面条件的有根树的方案数: 树所包含的所有节点值都在 pairs 中。 一个数对 [x i , y i ] 出现在 pairs 中 当且仅当 x…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 二分·树·traversal

bolt

答案摘要

class Solution: def checkWays(self, pairs: List[List[int]]) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个数组 pairs ,其中 pairs[i] = [xi, yi] ,并且满足:

  • pairs 中没有重复元素
  • xi < yi

令 ways 为满足下面条件的有根树的方案数:

  • 树所包含的所有节点值都在 pairs 中。
  • 一个数对 [xi, yi] 出现在 pairs 中 当且仅当 xi 是 yi 的祖先或者 yi 是 xi 的祖先。
  • 注意:构造出来的树不一定是二叉树。

两棵树被视为不同的方案当存在至少一个节点在两棵树中有不同的父节点。

请你返回:

  • 如果 ways == 0 ,返回 0 。
  • 如果 ways == 1 ,返回 1 。
  • 如果 ways > 1 ,返回 2 。

一棵 有根树 指的是只有一个根节点的树,所有边都是从根往外的方向。

我们称从根到一个节点路径上的任意一个节点(除去节点本身)都是该节点的 祖先 。根节点没有祖先。

 

示例 1:

输入:pairs = [[1,2],[2,3]]
输出:1
解释:如上图所示,有且只有一个符合规定的有根树。

示例 2:

输入:pairs = [[1,2],[2,3],[1,3]]
输出:2
解释:有多个符合规定的有根树,其中三个如上图所示。

示例 3:

输入:pairs = [[1,2],[2,3],[2,4],[1,5]]
输出:0
解释:没有符合规定的有根树。

 

提示:

  • 1 <= pairs.length <= 105
  • 1 <= xi < yi <= 500
  • pairs 中的元素互不相同。
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
    def checkWays(self, pairs: List[List[int]]) -> int:
        g = [[False] * 510 for _ in range(510)]
        v = defaultdict(list)
        for x, y in pairs:
            g[x][y] = g[y][x] = True
            v[x].append(y)
            v[y].append(x)
        nodes = []
        for i in range(510):
            if v[i]:
                nodes.append(i)
                g[i][i] = True
        nodes.sort(key=lambda x: len(v[x]))
        equal = False
        root = 0
        for i, x in enumerate(nodes):
            j = i + 1
            while j < len(nodes) and not g[x][nodes[j]]:
                j += 1
            if j < len(nodes):
                y = nodes[j]
                if len(v[x]) == len(v[y]):
                    equal = True
                for z in v[x]:
                    if not g[y][z]:
                        return 0
            else:
                root += 1
        if root > 1:
            return 0
        return 2 if equal else 1
speed

复杂度分析

指标
时间and space complexity depend on building adjacency maps and traversing all nodes, typically O(N + E), where N is the number of nodes and E is the number of pairs, but state tracking adds additional overhead in worst cases.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Looks for correct identification of the root node across all pairs.

  • question_mark

    Watches for proper handling of multiple valid reconstructions using state tracking.

  • question_mark

    Checks whether the traversal maintains consistent parent-child relationships across the tree.

warning

常见陷阱

外企场景
  • error

    Assuming any node with highest degree is root without verifying it connects to all others.

  • error

    Failing to track multiple valid parent candidates, missing multiple reconstructions.

  • error

    Overlooking conflicts in adjacency that make a tree impossible, returning incorrect counts.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Counting reconstructions for a tree with weighted edges.

  • arrow_right_alt

    Handling disconnected node pairs that cannot form a single rooted tree.

  • arrow_right_alt

    Extending to allow n-ary trees instead of strictly binary traversal.

help

常见问题

外企场景

重构一棵树的方案数题解:二分·树·traversal | LeetCode #1719 困难