LeetCode 687 Longest Univalue Path | Python Solution
LeetCode : https://leetcode.com/problems/longest-univalue-path/
Youtube Solution : Youtube Solution Link
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): longest_path = 0 def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ self.helper(root) return self.longest_path def helper(self,root) : if root is None : return 0 left = self.helper(root.left) right = self.helper(root.right) if root.left and root.left.val == root.val : left_path = 1 + left else: left_path = 0 if root.right and root.right.val == root.val: right_path = 1 + right else: right_path = 0 self.longest_path = max(self.longest_path,(left_path+right_path)) return max(left_path , right_path)
Comments
Post a Comment