298.Binary Tree Longest Consecutive Sequence
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).
For example,
1
\
3
/ \
2 4
\
5
Longest consecutive sequence path is3-4-5, so return3
Method 1 DFS, O(n) time, O(1) space.
- DFS from root to its children subtrees and update the target value by +1 each level down.
class Solution(object):
longest = 0
def longestConsecutive(self, root):
if not root:
return 0
def dfs(node, cur, target):
if not node:
return 0
if node.val == target:
cur += 1
else:
cur = 1
self.longest = max(self.longest, cur)
dfs(node.left, cur, node.val+1)
dfs(node.right, cur, node.val+1)
dfs(root, 0, root.val)
return self.longest