Before attempting this problem, you should be comfortable with:
Binary Tree Structure - Understanding how nodes connect via left and right children
Depth-First Search (DFS) - Traversing trees using both top-down and bottom-up recursive approaches
Passing State Through Recursion - Carrying information (parent value, sequence length) down or up the tree
1. Top Down Depth-first Search
Intuition
We traverse the tree from root to leaves, passing down the current consecutive sequence length to each child. At each node, we check if it continues the sequence from its parent (value is exactly one more than the parent). If so, we extend the sequence; otherwise, we start a new sequence. We track the maximum length seen across all nodes.
Algorithm
Initialize a global variable to track the maximum consecutive sequence length.
Define a DFS function that takes the current node, its parent, and the current sequence length.
If the current node is null, return.
If the current node's value equals the parent's value plus 1, increment the length; otherwise, reset it to 1.
Update the maximum length with the current length.
Recursively call DFS on both children, passing the current node as the parent.
classSolution{privatevar maxLength =0funclongestConsecutive(_ root:TreeNode?)->Int{
maxLength =0dfs(root,nil,0)return maxLength
}privatefuncdfs(_ p:TreeNode?,_ parent:TreeNode?,_ length:Int){guardlet p = p else{return}var len =1iflet parent = parent, p.val == parent.val +1{
len = length +1}
maxLength =max(maxLength, len)dfs(p.left, p, len)dfs(p.right, p, len)}}
Time & Space Complexity
Time complexity: O(n)
Space complexity: O(n)
Where n is the number of nodes in the input tree
2. Bottom Up Depth-first Search
Intuition
Instead of passing information down, we can compute the consecutive sequence length from leaves up to the root. Each node returns the length of the longest consecutive sequence starting from itself going downward. The parent then checks if it can extend this sequence by verifying that its value is exactly one less than its child's value.
Algorithm
Initialize a global variable to track the maximum consecutive sequence length.
Define a DFS function that returns the longest consecutive sequence starting from the current node.
If the current node is null, return 0.
Recursively get the sequence lengths from left and right children, adding 1 for the current node.
If the left child exists but doesn't form a consecutive sequence (current value + 1 != left value), reset the left length to 1.
Similarly check and potentially reset the right length.
Update the maximum length with the larger of the two lengths.
The problem asks for strictly increasing consecutive sequences where each child is exactly parent.val + 1. A common mistake is checking for any consecutive values (including decreasing) or allowing gaps.