Longest Univalue Path LeetCode solution in Python

1
class Solution:
2
max_path = 0
3

4
def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
5
self.dfs(root)
6
return self.max_path
7

8
def dfs(self, root):
9
if root is None:
10
return 0
11
left = self.dfs(root.left)
12
right = self.dfs(root.right)
13

14
if root.left and root.left.val == root.val:
15
leftPath = left + 1
16
else:
17
leftPath = 0
18

19
if root.right and root.right.val == root.val:
20
rightPath = right + 1
21
else:
22
rightPath = 0
23

24
self.max_path = max(self.max_path, leftPath + rightPath)
25
return max(leftPath, rightPath)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0