LeetCode 题解工作台

相邻字符不同的最长路径

给你一棵 树 (即一个连通、无向、无环图),根节点是节点 0 ,这棵树由编号从 0 到 n - 1 的 n 个节点组成。用下标从 0 开始、长度为 n 的数组 parent 来表示这棵树,其中 parent[i] 是节点 i 的父节点,由于节点 0 是根节点,所以 parent[0] == -1 。…

category

6

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

困难 · 图·搜索

bolt

答案摘要

我们先根据数组 构建邻接表 ,其中 表示节点 的所有子节点。 然后我们从根节点开始 DFS,对于每个节点 ,我们遍历 中的每个子节点 ,如果 $s[i] \neq s[j]$,那么我们就可以从 节点出发,经过 节点,到达某个叶子节点,这条路径的长度为 $x = 1 + dfs(j)$,我们用 记录最长的一条从节点 出发的路径长度。同时,在遍历的过程中,更新答案 $ans = \ma…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵 (即一个连通、无向、无环图),根节点是节点 0 ,这棵树由编号从 0n - 1n 个节点组成。用下标从 0 开始、长度为 n 的数组 parent 来表示这棵树,其中 parent[i] 是节点 i 的父节点,由于节点 0 是根节点,所以 parent[0] == -1

另给你一个字符串 s ,长度也是 n ,其中 s[i] 表示分配给节点 i 的字符。

请你找出路径上任意一对相邻节点都没有分配到相同字符的 最长路径 ,并返回该路径的长度。

 

示例 1:

输入:parent = [-1,0,0,1,1,2], s = "abacbe"
输出:3
解释:任意一对相邻节点字符都不同的最长路径是:0 -> 1 -> 3 。该路径的长度是 3 ,所以返回 3 。
可以证明不存在满足上述条件且比 3 更长的路径。 

示例 2:

输入:parent = [-1,0,0,0], s = "aabc"
输出:3
解释:任意一对相邻节点字符都不同的最长路径是:2 -> 0 -> 3 。该路径的长度为 3 ,所以返回 3 。

 

提示:

  • n == parent.length == s.length
  • 1 <= n <= 105
  • 对所有 i >= 10 <= parent[i] <= n - 1 均成立
  • parent[0] == -1
  • parent 表示一棵有效的树
  • s 仅由小写英文字母组成
lightbulb

解题思路

方法一:树形 DP

我们先根据数组 parentparent 构建邻接表 gg,其中 g[i]g[i] 表示节点 ii 的所有子节点。

然后我们从根节点开始 DFS,对于每个节点 ii,我们遍历 g[i]g[i] 中的每个子节点 jj,如果 s[i]s[j]s[i] \neq s[j],那么我们就可以从 ii 节点出发,经过 jj 节点,到达某个叶子节点,这条路径的长度为 x=1+dfs(j)x = 1 + dfs(j),我们用 mxmx 记录最长的一条从节点 ii 出发的路径长度。同时,在遍历的过程中,更新答案 ans=max(ans,mx+x)ans = \max(ans, mx + x)

最后,我们返回 ans+1ans + 1 即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为节点个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def longestPath(self, parent: List[int], s: str) -> int:
        def dfs(i: int) -> int:
            mx = 0
            nonlocal ans
            for j in g[i]:
                x = dfs(j) + 1
                if s[i] != s[j]:
                    ans = max(ans, mx + x)
                    mx = max(mx, x)
            return mx

        g = defaultdict(list)
        for i in range(1, len(parent)):
            g[parent[i]].append(i)
        ans = 0
        dfs(0)
        return ans + 1
speed

复杂度分析

指标
时间complexity is O(n) because each node is visited once during DFS. Space complexity is O(n) for the adjacency list and recursion stack. The approach scales linearly with tree size, avoiding redundant traversal of nodes or subtrees.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on graph indegree plus topological ordering.

  • question_mark

    Watch for combining two longest child paths at each node.

  • question_mark

    Verify edge cases where characters repeat consecutively along branches.

warning

常见陷阱

外企场景
  • error

    Counting paths with repeated adjacent characters.

  • error

    Ignoring second-longest child when combining paths through a node.

  • error

    Mismanaging recursion stack leading to excessive memory use.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the longest path where adjacent nodes differ by at least k characters in a string.

  • arrow_right_alt

    Compute the longest path in a k-ary tree with unique node labels.

  • arrow_right_alt

    Determine the maximum path length avoiding a specified subset of characters.

help

常见问题

外企场景

相邻字符不同的最长路径题解:图·搜索 | LeetCode #2246 困难