Program to find length of longest path with even sum in Python

When working with binary trees, we sometimes need to find the longest path where the sum of all node values is an even number. This problem requires tracking paths with even and odd sums separately using dynamic programming.

Problem Understanding

Given a binary tree, we need to find the length of the longest path whose sum is even. For example, in a tree with path [5, 2, 4, 8, 5], the sum is 24 (even) and the path length is 5.

2 5 4 8 2 5

Algorithm Approach

We use a recursive DFS approach that tracks two values for each node:

  • even_path: Length of longest path ending at this node with even sum
  • odd_path: Length of longest path ending at this node with odd sum

The key insight is that combining paths depends on the parity (even/odd) of the current node value.

Complete 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):
        def dfs(node):
            if not node:
                return 0, float("-inf")
            
            left_even, left_odd = dfs(node.left)
            right_even, right_odd = dfs(node.right)
            
            if node.val & 1:  # Current node is odd
                # Update global answer for paths through this node
                self.ans = max(self.ans, left_odd + right_even + 1, left_even + right_odd + 1)
                # Return updated even/odd path lengths
                return max(left_odd + 1, right_odd + 1, 0), max(left_even + 1, right_even + 1)
            else:  # Current node is even
                # Update global answer for paths through this node
                self.ans = max(self.ans, left_even + right_even + 1, left_odd + right_odd + 1)
                # Return updated even/odd path lengths  
                return max(left_even + 1, right_even + 1, 0), max(left_odd + 1, right_odd + 1)
        
        self.ans = 0
        dfs(root)
        return self.ans

# Test the solution
ob = Solution()
root = TreeNode(2)
root.left = TreeNode(5)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(5)

print(ob.solve(root))
5

How It Works

The algorithm works by maintaining two states at each node:

  • If current node is odd: Even paths become odd, odd paths become even
  • If current node is even: Even paths stay even, odd paths stay odd
  • We combine left and right subtree results to find the longest even-sum path passing through the current node
  • The function returns the best even and odd path lengths starting from the current node

Time and Space Complexity

  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(h) where h is the height of the tree (recursion stack)

Conclusion

This solution efficiently finds the longest even-sum path by tracking both even and odd path lengths at each node. The key insight is understanding how node parity affects path sum parity when combining subtree results.

Updated on: 2026-03-25T13:36:13+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements