Created
May 10, 2020 15:14
-
-
Save Desolve/2de59e38d37647b769952cc56f3fa375 to your computer and use it in GitHub Desktop.
0687 Longest Univalue Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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