Other simpler implementation is: def longestUnivaluePath(root: Optional[TreeNode]) -> int: if not root: return 0 res = [0] def helper(node, parent): if not node: return 0 left = helper(node.left, node) right = helper(node.right, node) res[0] = max(res[0], left + right) if parent and parent.val == node.val: return max(left, right) + 1 return 0 helper(root, None) return res[0]
Other simpler implementation is:
def longestUnivaluePath(root: Optional[TreeNode]) -> int:
if not root:
return 0
res = [0]
def helper(node, parent):
if not node:
return 0
left = helper(node.left, node)
right = helper(node.right, node)
res[0] = max(res[0], left + right)
if parent and parent.val == node.val:
return max(left, right) + 1
return 0
helper(root, None)
return res[0]
dang, I had the same code when I was solving it, but the editorial code seems much shorter