Problem Description
Given the root of a binary tree, return the length of the longest consecutive path in the tree. A consecutive path is one where the values of directly connected nodes differ by one. The path can be either increasing or decreasing, and it can change direction (child-parent-child) as long as the consecutive requirement holds.
Key Insights
- Use Depth-First Search (DFS) to visit every node.
- For each node, compute:
- The longest increasing consecutive path starting from that node.
- The longest decreasing consecutive path starting from that node.
- Combine the increasing and decreasing paths (subtracting one to avoid double counting the current node) to potentially form a longer consecutive sequence through the node.
- Update a global maximum to record the longest path seen.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes since every node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to the recursion stack.
Solution
The solution employs a DFS traversal. At every node, we calculate two values:
- inc – the length of the longest increasing consecutive sequence starting from that node.
- dec – the length of the longest decreasing consecutive sequence starting from that node.
For each child of the current node:
- If the child's value is node.val + 1, update the increasing sequence.
- If the child's value is node.val - 1, update the decreasing sequence.
Then, the longest path through the current node is inc + dec - 1 (subtracting one to avoid counting the current node twice). A global variable maintains the maximum length encountered. This process works regardless of the path direction because it combines both increasing and decreasing parts.