# 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 is 3-4-5, so return 3.
2
\
3
/
2
/
1
Longest consecutive sequence path is 2-3,not 3-2-1, so return 2.
The Idea: Run a DFS proceedure that maintains the current consequtive distance, and updates the maximum as you go along. If the root is non existant, return 0; otherwise begin with a consequtive distance of 1, and begin the recursive call. If the left or right child's value is 1 more than it's parent, increment the consecutive distance. Otherwise, reset back to 1 - and try again on that new subtree. In the end, we are just running a preorder traversal with a few additional checks.
Complexity: O(n) time and space
int longestConsecutive(TreeNode* root) {
int max_len = root ? 1 : 0;
_longestConsecutive(root, max_len, 1);
return max_len;
}
void _longestConsecutive(TreeNode* root, int &max_len, int cur_consec) {
if (root) {
if (root->left && root->left->val == root->val + 1) {
max_len = max(max_len, cur_consec + 1);
_longestConsecutive(root->left, max_len, cur_consec + 1);
}
else _longestConsecutive(root->left, max_len, 1);
if (root->right && root->right->val == root->val + 1) {
max_len = max(max_len, cur_consec + 1);
_longestConsecutive(root->right, max_len, cur_consec + 1);
}
else _longestConsecutive(root->right, max_len, 1);
}
}
Last modified 4yr ago