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

Suppose we have a binary tree. we have to find the length of the longest path whose sum is an even number.

So, if the input is like image, then the output will be 5, as the path is like [5, 2, 4, 8, 5], sum = 24(even).

To solve this, we will follow these steps −

• Define a function dfs() . This will take node
• if node is null, then
• return a pair (0, -inf)
• (left_0, left_1) := dfs(left of node)
• (right_0, right_1) := dfs(right of node)
• if value of node is odd, then
• ans := maximum of ans, (left_1 + right_0 + 1) and (left_0 + right_1 + 1)
• return a pair (maximum of (left_1 + 1), (right_1 + 1) and 0) , maximum of (left_0 + 1) and (right_0 + 1))
• otherwise,
• ans := maximum of ans, (left_0 + right_0 + 1) and (left_1 + right_1 + 1)
• return a pair (maximum of (left_0 + 1), (right_0 + 1), 0) , maximum of (left_1 + 1), (right_1 + 1))
• From the main method do the following −
• ans := 0
• dfs(root)
• return ans

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

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_0, left_1 = dfs(node.left)
right_0, right_1 = dfs(node.right)
if node.val & 1:
self.ans = max(self.ans, left_1 + right_0 + 1, left_0 + right_1 + 1)
return max(left_1 + 1, right_1 + 1, 0), max(left_0 + 1, right_0 + 1)
else:
self.ans = max(self.ans, left_0 + right_0 + 1, left_1 + right_1 + 1)
return max(left_0 + 1, right_0 + 1, 0), max(left_1 + 1, right_1 + 1)
self.ans = 0
dfs(root)
return self.ans
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))

## Input

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)

## Output

5