This problem asks to find the length of the longest consecutive sequence in a binary tree. A consecutive sequence is defined as a path where the absolute difference between consecutive nodes is 1. The path can be either increasing or decreasing.
The solution employs a Depth-First Search (DFS) approach. The core idea is to recursively traverse the tree and, for each node, calculate the length of the longest increasing and decreasing sequences ending at that node. This information is then used to update the overall maximum length found so far.
Algorithm:
dfs(root)
Function: This recursive function takes a tree node as input and returns a two-element array [incr, decr]
. incr
represents the length of the longest increasing sequence ending at root
, and decr
represents the length of the longest decreasing sequence ending at root
.
Base Case: If the root
is null
(empty subtree), it returns [0, 0]
.
Recursive Step:
dfs()
on the left and right children to get their respective [incr, decr]
values.root.left.val + 1 == root.val
, it means an increasing sequence can be extended from the left child. Similarly for decreasing sequences and right child.incr
and decr
) are updated based on the children's values.Global Maximum: A global variable ans
keeps track of the maximum length found so far. After updating incr
and decr
for a node, ans
is updated with the maximum of ans
and incr + decr -1
. The -1
is because the node itself is counted twice (once in incr
and once in decr
).
Return Value: The function returns the calculated [incr, decr]
values for the current node.
Time Complexity Analysis:
The dfs
function visits each node in the tree exactly once. Therefore, the time complexity is O(N), where N is the number of nodes in the binary tree.
Space Complexity Analysis:
The space complexity is determined by the recursion depth. In the worst case (a skewed tree), the recursion depth can be equal to the height of the tree, which is O(N) in the worst case (a skewed tree). In the average case for a balanced tree it would be O(log N). The space used to store the [incr, decr]
arrays during recursion is also O(H), where H is the height of the tree. Therefore, the overall space complexity is O(N) in the worst case and O(logN) in the average case.
Code Examples (Python, Java, C++, Go):
The provided code snippets in Python, Java, C++, and Go implement the algorithm described above. Each snippet follows the same logic but uses the syntax specific to its respective language. They all have the same time and space complexities.