Program to find length of longest consecutive path of a binary tree in python

Suppose we have a binary tree; we have to find the longest consecutive path in the binary tree. A consecutive path is a sequence of nodes where each node's value differs from the previous by exactly 1 (either increasing or decreasing).

So, if the input is like

3 2 4 5 9 6 Longest path: 2?3?4?5?6 (length=5)

then the output will be 5 as longest consecutive sequence is [2, 3, 4, 5, 6].

Algorithm

To solve this, we use a depth-first search (DFS) approach that tracks both increasing and decreasing consecutive paths ?

  • For each node, calculate the longest increasing and decreasing paths starting from that node
  • Check if we can form a longer path by connecting left and right subtrees through the current node
  • Keep track of the maximum path length found so far

Implementation

class TreeNode:
    def __init__(self, data, left = None, right = None):
        self.val = data
        self.left = left
        self.right = right

class Solution:
    def solve(self, root):
        if not root:
            return 0
        self.maxPath = 0

        def helper(node):
            inc, dec = 1, 1
            if node.left:
                left_inc, left_dec = helper(node.left)
            else:
                left_inc, left_dec = 0, 0
            if node.right:
                right_inc, right_dec = helper(node.right)
            else:
                right_inc, right_dec = 0, 0

            if node.left and node.val - node.left.val == 1:
                inc = max(inc, left_inc + 1)
            elif node.left and node.val - node.left.val == -1:
                dec = max(dec, left_dec + 1)

            if node.right and node.val - node.right.val == 1:
                inc = max(inc, right_inc + 1)
            elif node.right and node.val - node.right.val == -1:
                dec = max(dec, right_dec + 1)

            if (node.left and node.right and node.left.val - node.val == 1 and node.val - node.right.val == 1):
                self.maxPath = max(self.maxPath, left_dec + right_inc + 1)
            elif (node.left and node.right and node.left.val - node.val == -1
                  and node.val - node.right.val == -1):
                self.maxPath = max(self.maxPath, left_inc + right_dec + 1)
                
            self.maxPath = max(self.maxPath, inc, dec)
            return inc, dec

        helper(root)
        return self.maxPath

# Test the solution
ob = Solution()
root = TreeNode(3)
root.left = TreeNode(2)
root.right = TreeNode(4)
root.right.left = TreeNode(5)
root.right.right = TreeNode(9)
root.right.left.left = TreeNode(6)
print(ob.solve(root))

The output of the above code is ?

5

How It Works

The algorithm uses a recursive helper function that returns two values for each node ?

  • inc − longest increasing consecutive path starting from current node
  • dec − longest decreasing consecutive path starting from current node

For each node, we check if we can extend consecutive paths from children nodes. We also check if we can form a longer path by connecting paths from left and right subtrees through the current node.

Example Walkthrough

For the tree with path [2, 3, 4, 5, 6] ?

# Create a simple example
ob = Solution()
root = TreeNode(4)
root.left = TreeNode(3)
root.right = TreeNode(5)
root.left.left = TreeNode(2)
root.right.right = TreeNode(6)
print(f"Longest consecutive path: {ob.solve(root)}")
Longest consecutive path: 3

Conclusion

This solution efficiently finds the longest consecutive path in a binary tree using DFS traversal. The time complexity is O(n) where n is the number of nodes, as we visit each node once.

Updated on: 2026-03-25T13:06:20+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements