{x}
blog image

Binary Tree Longest Consecutive Sequence

Solution Explanation:

This problem asks to find the length of the longest consecutive sequence path in a binary tree. A consecutive sequence path is defined as a path where node values increase by one from parent to child. The path can start at any node.

The solution uses Depth-First Search (DFS) to traverse the tree. The core idea is to recursively explore the tree, keeping track of the length of the consecutive sequence from a given node downwards.

Approach:

  1. DFS Function (dfs): A recursive function dfs is defined. It takes a tree node as input and returns the length of the longest consecutive sequence starting from that node.

  2. Base Case: If the current node is null (empty), it returns 0.

  3. Recursive Calls: It recursively calls dfs on the left and right children of the current node. It adds 1 to the lengths returned by the recursive calls because the current node extends the sequence by 1.

  4. Consecutive Sequence Check: It checks if the values of the children are consecutive to the current node's value. If not, it resets the length from that child to 1, indicating a break in the consecutive sequence.

  5. Maximum Length: It takes the maximum of the lengths from the left and right subtrees (max(l, r)) and updates a global variable ans (initialized to 0 outside the dfs function) to keep track of the overall longest consecutive sequence found so far.

  6. Return Value: The function returns the length of the consecutive sequence starting from the current node.

  7. Main Function: The main function simply calls dfs on the root of the tree and returns the final ans.

Time and Space Complexity Analysis:

  • Time Complexity: O(N), where N is the number of nodes in the tree. This is because each node is visited exactly once during the DFS traversal.

  • Space Complexity: O(H), where H is the height of the tree. This is due to the recursive call stack used in the DFS. In the worst case (a skewed tree), H could be equal to N, resulting in O(N) space complexity. In the best case (a balanced tree), H would be log₂(N), leading to O(log₂(N)) space complexity.

Code Explanation (Python Example):

The Python code implements the described approach. Let's break it down:

class Solution:
    def longestConsecutive(self, root: Optional[TreeNode]) -> int:
        def dfs(root: Optional[TreeNode]) -> int:
            if root is None:
                return 0
            l = dfs(root.left) + 1
            r = dfs(root.right) + 1
            if root.left and root.left.val - root.val != 1:
                l = 1
            if root.right and root.right.val - root.val != 1:
                r = 1
            t = max(l, r)
            nonlocal ans
            ans = max(ans, t)
            return t
 
        ans = 0
        dfs(root)
        return ans
  • The longestConsecutive function initializes ans to 0 and calls the dfs helper function.

  • The dfs function recursively explores the tree, updating ans with the maximum consecutive sequence length encountered. The nonlocal ans keyword is crucial to allow modification of the ans variable defined in the outer scope.

The code in other languages (Java, C++, Go, TypeScript) follows the same logic and differs only in syntax. The core algorithm remains consistent.