LeetCode 题解工作台
相邻字符不同的最长路径
给你一棵 树 (即一个连通、无向、无环图),根节点是节点 0 ,这棵树由编号从 0 到 n - 1 的 n 个节点组成。用下标从 0 开始、长度为 n 的数组 parent 来表示这棵树,其中 parent[i] 是节点 i 的父节点,由于节点 0 是根节点,所以 parent[0] == -1 。…
6
题型
5
代码语言
3
相关题
当前训练重点
困难 · 图·搜索
答案摘要
我们先根据数组 构建邻接表 ,其中 表示节点 的所有子节点。 然后我们从根节点开始 DFS,对于每个节点 ,我们遍历 中的每个子节点 ,如果 $s[i] \neq s[j]$,那么我们就可以从 节点出发,经过 节点,到达某个叶子节点,这条路径的长度为 $x = 1 + dfs(j)$,我们用 记录最长的一条从节点 出发的路径长度。同时,在遍历的过程中,更新答案 $ans = \ma…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
给你一棵 树(即一个连通、无向、无环图),根节点是节点 0 ,这棵树由编号从 0 到 n - 1 的 n 个节点组成。用下标从 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.length1 <= n <= 105- 对所有
i >= 1,0 <= parent[i] <= n - 1均成立 parent[0] == -1parent表示一棵有效的树s仅由小写英文字母组成
解题思路
方法一:树形 DP
我们先根据数组 构建邻接表 ,其中 表示节点 的所有子节点。
然后我们从根节点开始 DFS,对于每个节点 ,我们遍历 中的每个子节点 ,如果 ,那么我们就可以从 节点出发,经过 节点,到达某个叶子节点,这条路径的长度为 ,我们用 记录最长的一条从节点 出发的路径长度。同时,在遍历的过程中,更新答案 。
最后,我们返回 即可。
时间复杂度 ,空间复杂度 。其中 为节点个数。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.