Problem Description
Given the root of a binary tree, return the length of the longest consecutive sequence path. A consecutive sequence path is defined as a path where each node's value is exactly one more than its parent's value. The path can start at any node in the tree, but you can only travel from parent to child.
Key Insights
- Use a Depth-First Search (DFS) to traverse the binary tree.
- Pass the current node’s value and the length of the current consecutive sequence in the recursive call.
- When a node’s value is exactly one greater than its parent’s value, increment the sequence length; otherwise, reset it to 1.
- Keep track of the maximum sequence length found during the traversal.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes in the tree, since each node is visited once.
Space Complexity: O(H), where H is the height of the tree. In the worst-case of a skewed tree, the recursion stack can be O(N).
Solution
The solution involves using DFS to explore every node in the binary tree while keeping track of the length of the consecutive sequence. For each node, if the node's value is one greater than its parent’s value, we increment the sequence length; otherwise, we reset the sequence length to 1. During the traversal, a global variable is updated if the current sequence length exceeds the previously recorded maximum. This approach ensures that every possible consecutive path is considered.