# 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

```cpp
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);

    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/298-binary-tree-longest-consecutive-sequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
