Skip to content

Commit e65adf1

Browse files
committed
Time: 3 ms (81.43%), Space: 18.4 MB (99.35%) - LeetHub
1 parent 01e2955 commit e65adf1

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
from typing import List, Optional
4+
5+
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
13+
class Solution:
14+
def longestConsecutive(self, root: Optional[TreeNode]) -> int:
15+
def longestPath(root: TreeNode) -> List[int]:
16+
nonlocal maxval
17+
18+
if not root:
19+
return [0, 0]
20+
21+
increase = decrease = 1
22+
if root.left:
23+
left = longestPath(root.left)
24+
if (root.val == root.left.val + 1):
25+
decrease = left[1] + 1
26+
elif (root.val == root.left.val - 1):
27+
increase = left[0] + 1
28+
29+
if root.right:
30+
right = longestPath(root.right)
31+
if (root.val == root.right.val + 1):
32+
decrease = max(decrease, right[1] + 1)
33+
elif (root.val == root.right.val - 1):
34+
increase = max(increase, right[0] + 1)
35+
36+
maxval = max(maxval, decrease + increase - 1)
37+
return [increase, decrease]
38+
39+
maxval = 0
40+
longestPath(root)
41+
return maxval
42+
43+
44+
root = TreeNode(1)
45+
root.left = TreeNode(2)
46+
root.left.left = TreeNode(3)
47+
root.left.right = TreeNode(4)
48+
root.right = TreeNode(5)
49+
root.right.right = TreeNode(6)
50+
print(Solution().longestConsecutive(root))

0 commit comments

Comments
 (0)