-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path298 Binary Tree Longest Consecutive Sequence.py
60 lines (49 loc) · 1.35 KB
/
298 Binary Tree Longest Consecutive Sequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Premium Question
Recursive
Longest Consecutive Subsequence in BT
Author: Rajeev Ranjan
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.gmax = 0
def longestConsecutive(self, root):
self.longest(root)
return self.gmax
def longest(self, cur):
"""
longest ended at root
Only consider increasing order
"""
if not cur:
return 0
maxa = 1
l = self.longest(cur.left)
r = self.longest(cur.right)
if cur.left and cur.val+1 == cur.left.val:
maxa = max(maxa, l+1)
if cur.right and cur.val+1 == cur.right.val:
maxa = max(maxa, r+1)
self.gmax = max(self.gmax, maxa)
return maxa
def longestConsecutive_error(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
maxa = 1
l = self.longestConsecutive(root.left)
r = self.longestConsecutive(root.right)
maxa = max(maxa, l, r)
if root.left and root.val + 1 == root.left.val:
maxa = max(maxa, l+1)
if root.right and root.val + 1 == root.right.val:
maxa = max(maxa, r+1)
return maxa