298 Binary Tree Longest Consecutive Sequence
1
\
3
/ \
2 4
\
5 2
\
3
/
2
/
1Last updated
1
\
3
/ \
2 4
\
5 2
\
3
/
2
/
1Last updated
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);
}
}