Skip to content

Instantly share code, notes, and snippets.

@Desolve
Created May 10, 2020 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/2de59e38d37647b769952cc56f3fa375 to your computer and use it in GitHub Desktop.
Save Desolve/2de59e38d37647b769952cc56f3fa375 to your computer and use it in GitHub Desktop.
0687 Longest Univalue Path
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.mx = 0
def longestUnivaluePath(self, root: TreeNode) -> int:
if not root: return 0
self.count(root, root.val)
return self.mx
def count(self, root: TreeNode, val: int) -> int:
if not root: return 0
l, r = self.count(root.left, root.val), self.count(root.right, root.val)
self.mx = max(self.mx, l + r)
return 0 if root.val != val else max(l, r) + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment