# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:deflongestUnivaluePath(self,root: TreeNode) ->int: res =float('-inf')defdfs(node):if node isNone:returndict() value = node.val left_map =dfs(node.left) right_map =dfs(node.right) total = left_map.get(value, 0)+ right_map.get(value, 0)+1nonlocal res res =max(res, total)return{value:1+max(left_map.get(value, 0), right_map.get(value, 0))}dfs(root)return res -1if res !=float('-inf')else0