Longest Univalue Path LeetCode solution in Python
1class Solution:2max_path = 034def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:5self.dfs(root)6return self.max_path78def dfs(self, root):9if root is None:10return 011left = self.dfs(root.left)12right = self.dfs(root.right)1314if root.left and root.left.val == root.val:15leftPath = left + 116else:17leftPath = 01819if root.right and root.right.val == root.val:20rightPath = right + 121else:22rightPath = 02324self.max_path = max(self.max_path, leftPath + rightPath)25return max(leftPath, rightPath)