SDE & MLE Prep

687. Longest Univalue Path

Problem

Return the number of edges in the longest path in which every node has the same value. The path need not pass through the root.

Example: [5,4,5,1,1,null,5] → 2; [1,4,5,4,4,null,5] → 2

Like the diameter: each node returns the longest downward arm with its own value. Arms from children count only if the child has the same value; update the global with left + right.

Complexity: O(n).

class Solution:
    def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
        best = 0

        def arm(node):
            nonlocal best
            if not node:
                return 0
            l, r = arm(node.left), arm(node.right)
            l = l + 1 if node.left and node.left.val == node.val else 0
            r = r + 1 if node.right and node.right.val == node.val else 0
            best = max(best, l + r)
            return max(l, r)

        arm(root)
        return best