687. Longest Univalue Path

687. Longest Univalue Path

# 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 depth(self,root):
        if root==None:return 0
        r,l=self.depth(root.right),self.depth(root.left)
        if root.left:
            if root.val!=root.left.val:l=0
            else:l+=1
        if root.right:
            if root.val!=root.right.val:r=0
            else:r+=1
        self.ans=max(self.ans,l+r)
        return max(l,r)
            
    def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
        self.ans=0
        self.depth(root)
        return self.ans

l,r别写错

你可能感兴趣的:(leetcode)