难度: Medium
原题连接
内容描述
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
Example 1:
Input:
1
\
3
/ \
2 4
\
5
Output: 3
Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
Example 2:
Input:
2
\
3
/
2
/
1
Output: 2
Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******
Top down
beats 94.30%
class Solution:
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(node, parent, length):
if not node:
return
length = length + 1 if parent and node.val == parent.val + 1 else 1
self.max_len = max(self.max_len, length)
helper(node.left, node, length)
helper(node.right, node, length)
self.max_len = 0
helper(root, None, 0)
return self.max_len
思路 2 - 时间复杂度: O(N)- 空间复杂度: O(N)******
Bottom Up
beats 54.37%
class Solution:
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(node):
if not node:
return 0
L = helper(node.left) + 1
R = helper(node.right) + 1
if node.left and node.val + 1 != node.left.val:
L = 1
if node.right and node.val + 1 != node.right.val:
R = 1
length = max(L, R)
self.max_len = max(self.max_len, length)
return length
self.max_len = 0
helper(root)
return self.max_len