File tree Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Given a binary tree, find the length of the longest consecutive sequence path.
3
+
4
+ The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child
5
+ connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
6
+
7
+ For example,
8
+ 1
9
+ \
10
+ 3
11
+ / \
12
+ 2 4
13
+ \
14
+ 5
15
+ Longest consecutive sequence path is 3-4-5, so return 3.
16
+ 2
17
+ \
18
+ 3
19
+ /
20
+ 2
21
+ /
22
+ 1
23
+ Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
24
+
25
+ """
26
+ __author__ = 'Daniel'
27
+
28
+
29
+ class TreeNode (object ):
30
+ def __init__ (self , x ):
31
+ self .val = x
32
+ self .left = None
33
+ self .right = None
34
+
35
+
36
+ class Solution (object ):
37
+ def __init__ (self ):
38
+ self .maxa = 0
39
+
40
+ def longestConsecutive (self , root ):
41
+ self .longest (root )
42
+ return self .maxa
43
+
44
+ def longest (self , root ):
45
+ """
46
+ longest ended at root
47
+ """
48
+ if not root :
49
+ return 0
50
+
51
+ maxa = 1
52
+ l = self .longest (root .left )
53
+ r = self .longest (root .right )
54
+ if root .left and root .val + 1 == root .left .val :
55
+ maxa = max (maxa , l + 1 )
56
+ if root .right and root .val + 1 == root .right .val :
57
+ maxa = max (maxa , r + 1 )
58
+
59
+ self .maxa = max (self .maxa , maxa )
60
+ return maxa
61
+
62
+ def longestConsecutive_error (self , root ):
63
+ """
64
+ :type root: TreeNode
65
+ :rtype: int
66
+ """
67
+ if not root :
68
+ return 0
69
+
70
+ maxa = 1
71
+ l = self .longestConsecutive (root .left )
72
+ r = self .longestConsecutive (root .right )
73
+ maxa = max (maxa , l , r )
74
+ if root .left and root .val + 1 == root .left .val :
75
+ maxa = max (maxa , l + 1 )
76
+ if root .right and root .val + 1 == root .right .val :
77
+ maxa = max (maxa , r + 1 )
78
+
79
+ return maxa
You can’t perform that action at this time.
0 commit comments