This is an simple problem. For each node, if its left node and right node has no same value as itself, then the longest path with its value in the sub-tree is 0. And other cases are just something very likely. So we could solve it recursivly.
Note that, for sub-tree with structure:
4 / \ 4 4
When visiting the top 4 node, the total path would be right path length plus left path length plus 2.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: return self._helper(root) def _helper(self, node): if node is None: return None, 0, 0 l = self._helper(node.left) r = self._helper(node.right) root = max(l, r) if l == r == node.val: non_root = max(l, r) + 1 root = max(l + r + 2, root) elif l == node.val: non_root = l + 1 elif r == node.val: non_root = r + 1 else: non_root = 0 root = max(non_root, root) return node.val, non_root, root