687. 最长同值路径
题目链接 | 687. 最长同值路径 |
---|---|
思路 | “树的直径”的简单变体 |
题解链接 | 【视频】彻底掌握直径 DP!从二叉树到一般树!(Python/Java/C++/Go) |
关键点 | 注意维护当前状态:当左二子的值与本节点值不同时,要更新\(v_{l} = 0\) |
时间复杂度 | \(O(n)\) |
空间复杂度 | \(O(n)\) |
代码实现:
class Solution:
def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
answer = 0
def dfs(node):
if node is None:
return -1
l_len = dfs(node.left) + 1
r_len = dfs(node.right) + 1
if node.left and node.left.val != node.val:
l_len = 0
if node.right and node.right.val != node.val:
r_len = 0
nonlocal answer
answer = max(answer, l_len + r_len)
return max(l_len, r_len)
dfs(root)
return answer