Program to find longest even value path of a binary tree in Python

A Binary tree is one of the data structures in Python in which each element is known as a Node. Each node should have a minimum of two child nodes. These children nodes are called as left child and the right child.

The top node of the binary tree is known as the Root Node, and the nodes with no children are called Leaf Nodes. Following is the representation of the Binary Tree in Python ?

      10
     /  \
    5    15
   / \     \
  2   7     20

Where,

  • 10 is the root Node.
  • 5 is the left child of 10.
  • 15 is the right child of 10.
  • 2 and 7 are the children of Node 5.
  • 20 is the Leaf Node.

Creating a Binary Tree

Following is the example which creates a Binary tree in Python with 1 as the root node and 2, 3 as the child nodes ?

class TreeNode:
    def __init__(self, value):
        self.value = value      # The data in the node
        self.left = None        # Left child
        self.right = None       # Right child

# Create nodes
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print(f"Root: {root.value}")
print(f"Left child: {root.left.value}")
print(f"Right child: {root.right.value}")
Root: 1
Left child: 2
Right child: 3

Below is the manual representation of the above Binary Tree ?

    1
   / \
  2   3

Finding the Longest Even Path of Binary Tree

The longest even path in a binary tree is the longest path such that every node along that path has an even value. A path is a sequence of connected nodes in the tree from parent to child, not necessarily from root to leaf.

The length is measured by the number of edges, not nodes, and only nodes with even values are allowed in the path. Let's consider the following Binary Tree and explore all possible paths with only even value nodes ?

        2
       / \
     10   4
         / \
        8   2
       /
      6

Following are the possible even value paths of the Binary Tree ?

  • 2 ? 10 --- length = 1
  • 2 ? 4 --- length = 1
  • 4 ? 8 ? 6 --- length = 2
  • 2 ? 4 ? 8 ? 6 --- length = 3
  • 4 ? 2 --- length = 1
  • 2 ? 4 ? 2 --- length = 2

Among all the above possibilities longest even path of the given binary Tree is 2, 4, 8, 6 with length 3.

Algorithm Implementation

The algorithm uses depth-first search (DFS) to traverse the tree and track the longest even path. For each node, we calculate the maximum path through left and right subtrees ?

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

class Solution:
    def __init__(self):
        self.max_length = 0
    
    def longest_even_path(self, root):
        def dfs(node):
            if not node:
                return 0
            
            # Recur for left and right children
            left_len = dfs(node.left)
            right_len = dfs(node.right)
            
            # Only process current node if it's even
            if node.value % 2 == 0:
                left = left_len if node.left and node.left.value % 2 == 0 else 0
                right = right_len if node.right and node.right.value % 2 == 0 else 0
                
                # Update global max path length
                self.max_length = max(self.max_length, left + right)
                
                return max(left, right) + 1
            else:
                return 0
        
        dfs(root)
        return self.max_length

# Create the example tree
root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)

# Run the solution
sol = Solution()
length = sol.longest_even_path(root)

print("Longest Even Value Path Length:", length)
Longest Even Value Path Length: 3

How the Algorithm Works

The algorithm works in the following steps:

  • DFS Traversal: Visit each node using depth-first search
  • Even Check: Process only nodes with even values
  • Path Calculation: For each even node, calculate the longest path through its left and right subtrees
  • Global Maximum: Track the maximum path length found so far

Alternative Implementation

Here's a more detailed version that also returns the actual path ?

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

def find_longest_even_path_with_nodes(root):
    max_length = 0
    longest_path = []
    
    def dfs(node):
        nonlocal max_length, longest_path
        if not node or node.value % 2 != 0:
            return []
        
        # Get paths from left and right subtrees
        left_paths = dfs(node.left) if node.left else []
        right_paths = dfs(node.right) if node.right else []
        
        # Current node starts a new path
        current_path = [node.value]
        
        # Extend with longest left path
        if left_paths:
            current_path.extend(left_paths)
        
        # Check if we can combine left and right paths through current node
        combined_length = len(left_paths) + len(right_paths) + 1
        if combined_length > max_length:
            max_length = combined_length
            longest_path = left_paths[::-1] + [node.value] + right_paths
        
        # Return the longer path for parent
        if len(left_paths) >= len(right_paths):
            return [node.value] + left_paths
        else:
            return [node.value] + right_paths
    
    dfs(root)
    return max_length - 1, longest_path  # -1 because we count edges, not nodes

# Test with the example tree
root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)

length, path = find_longest_even_path_with_nodes(root)
print(f"Longest Even Path Length: {length}")
print(f"Path nodes: {' ? '.join(map(str, path))}")
Longest Even Path Length: 3
Path nodes: 2 ? 4 ? 8 ? 6

Conclusion

The longest even path problem uses DFS to traverse the binary tree and track paths containing only even-valued nodes. The algorithm efficiently finds the maximum path length by considering all possible even paths and returns the length of edges in the longest sequence.

Updated on: 2026-03-25T11:20:50+05:30

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements