## DEV Community

Abhishek Chaudhary

Posted on

# Longest Univalue Path

Given the `root` of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.

The length of the path between two nodes is represented by the number of edges between them.

Example 1:

Input: root = [5,4,5,1,1,5]
Output: 2

Example 2:

Input: root = [1,4,5,4,4,5]
Output: 2

Constraints:

• The number of nodes in the tree is in the range `[0, 104]`.
• `-1000 <= Node.val <= 1000`
• The depth of the tree will not exceed `1000`.

SOLUTION:

``````# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def mlen(self, root):
if not root:
return 0
l = self.mlen(root.left)
r = self.mlen(root.right)
mpath = 1
if root.left and root.left.val == root.val:
mpath = max(mpath, 1 + l)
self.pathlen = max(self.pathlen, 1 + l)
if root.right and root.right.val == root.val:
mpath = max(mpath,  1 + r)
self.pathlen = max(self.pathlen, 1 + r)
if root.left and root.right and root.val == root.left.val == root.right.val:
self.pathlen = max(self.pathlen, l + r + 1)
return mpath

def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
self.pathlen = 0
self.mlen(root)
return max(self.pathlen - 1, 0)
``````