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

Suppose we have a binary tree, we have to find the longest path that alternates between left and right child and going down. An alternating path means we switch between going left and right at each level.

So, if the input is like ?

2 3 4 5 6 7 8 Alternating path: [2, 4, 5, 7, 8] = Length 5

then the output will be 5 as the alternating path is [2, 4, 5, 7, 8].

Algorithm

To solve this, we will follow these steps ?

  • If root is null, return 0
  • Define a recursive function dfs() that takes node, count, and flag parameters
  • The flag indicates the direction we came from (True for left, False for right)
  • For each node, try both alternating directions and take the maximum
  • Return the maximum path length starting from left and right children of root

Implementation

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

class Solution:
    def solve(self, root):
        if not root:
            return 0
        
        def dfs(node, count, flag):
            if not node:
                return count
            
            if flag:  # Came from left, so continue alternating
                a = dfs(node.left, count + 1, False)
                b = dfs(node.right, 1, True)
            else:  # Came from right, so continue alternating
                a = dfs(node.right, count + 1, True)
                b = dfs(node.left, 1, False)
            
            return max(a, b)
        
        # Start from both children of root
        left_path = dfs(root.left, 1, False)
        right_path = dfs(root.right, 1, True)
        
        return max(left_path, right_path)

# Create the binary tree
ob = Solution()
root = TreeNode(2)
root.left = TreeNode(3)
root.right = TreeNode(4)
root.right.left = TreeNode(5)
root.right.right = TreeNode(6)
root.right.left.right = TreeNode(7)
root.right.left.right.left = TreeNode(8)

print(ob.solve(root))
5

How It Works

The algorithm uses depth-first search with a flag to track the alternating pattern ?

  • Flag True: We came from left child, so we continue left and reset right
  • Flag False: We came from right child, so we continue right and reset left
  • For each node, we calculate both possible paths and return the maximum
  • The count parameter tracks the current path length

Conclusion

This solution efficiently finds the longest alternating path in a binary tree using DFS with a time complexity of O(n). The key insight is tracking the direction flag to ensure proper alternation between left and right movements.

Updated on: 2026-03-25T12:54:09+05:30

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements