Longest ZigZag Path in a Binary Tree [Medium]

20 Sep 2026, Updated: 25 Sep 2026 2 min read
2
The Longest ZigZag Path in a Binary Tree problem requires finding the longest path where the direction alternates between left and right at every step.

Problem

Given the root of a binary tree, a ZigZag path starts at any node and follows these rules: if the previous move was to the left, the next move must be to the right, and if the previous move was to the right, the next move must be to the left.

The length of a ZigZag path is the number of edges in the path. Return the length of the longest ZigZag path in the tree.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
root:
        1
       / \
      1   1
         / \
        1   1
         \
          1
Output
3

Example 2

Input
root:
       1
      /
     1
    /
   1
Output
1

Solution

This solution uses Depth-First Search (DFS). For every node, we maintain two values: the length of the ZigZag path if the next move is to the left, and the length if the next move is to the right.

If we move left, the next move must be right, so the left ZigZag length is calculated from the right direction of the child. Similarly, if we move right, the next move must be left.
class Solution {
    int max = 0;

    public int longestZigZag(TreeNode root) {
        dfs(root, true, 0);
        dfs(root, false, 0);
        return max;
    }

    private void dfs(TreeNode node, boolean isLeftNode, int length) {
        if (node == null) {
            return;
        }

        max = Math.max(max, length);

        if (isLeftNode) {
            dfs(node.left, true, 1);
            dfs(node.right, false, length + 1);
        } else {
            dfs(node.right, false, 1);
            dfs(node.left, true, length + 1);
        }
    }
}

Complexity

Each node is visited a constant number of times, so the time complexity is O(n), where n is the number of nodes in the binary tree.

The DFS recursion uses space proportional to the height of the tree, so the extra space complexity is O(h), where h is the height of the tree.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion