Browse curriculum

Longest ZigZag Path in a Binary Tree (LeetCode 1372)

Longest ZigZag Path in a Binary Tree (LeetCode 1372): find the longest path that alternates left and right steps. A DFS carries two lengths into each node: the zigzag that arrived by a left step and the one that arrived by a right step.

Problem Understanding

Longest ZigZag Path in a Binary Tree (LeetCode 1372): a zigzag path starts at any node, picks a direction (left or right), and moves to that child, then switches direction at every step until it cannot continue. Its length is the number of nodes visited minus one. Return the length of the longest zigzag path in the tree.

Examples: [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1] → 3 (right → left → right); [1,1,1,null,1,null,null,1,1,null,1] → 4 (left → right → left → right); [1] → 0.

The Intuition: Carry Both Directions Down

Every zigzag ends somewhere, arriving at its last node by either a left step or a right step. So pass two numbers down the tree: how long the zigzag is that arrives here by a left step, and by a right step.

  1. Start with dfs(root, 0, 0).
  2. At each node, update best with both lengths.
  3. Going left continues the path that arrived by a right step: the left child gets (right + 1, 0).
  4. Going right continues the path that arrived by a left step: the right child gets (0, left + 1).

This is the passing values down form of DFS, like Count Good Nodes in Binary Tree, which passes the path maximum down instead.

Longest ZigZag Path in a Binary Tree Visualization

L = LENGTH ARRIVING BY A LEFT STEP · R = BY A RIGHT STEP · GREEN = BEST ZIGZAG

dfs(root, 0, 0)

left

:

right

:

best

0

call stack (root first)

No calls in progress

 

dfs(root 1, left = 0, right = 0): no step taken yet

Next

1: arrived with left = 0, right = 0. Best stays 0. The left child gets (0 + 1, 0); the right child gets (0, 0 + 1)

Free preview: the first 3 of 9 steps

Tree

Under each visited node, L and R are the lengths it was called with. The best zigzag so far is green. Every value in LeetCode’s examples is 1, so the presets number the nodes instead; only the shape matters. Try Straight line, where no direction ever changes.

Longest ZigZag Path in a Binary Tree Dry Run

Input: LeetCode example 2’s shape, numbered: [1,2,3,null,4,null,null,5,6,null,7]. Nodes in visit order:

Node left right best
1 0 0 0
2 1 0 1
4 0 2 2
5 3 0 3
7 0 4 4
6 0 1 4
3 0 1 4

The longest zigzag is 1 → 2 → 4 → 5 → 7: left, right, left, right.

Answer: 4.

Longest ZigZag Path in a Binary Tree LeetCode Solution

One DFS with two lengths as parameters and a running best.

Longest ZigZag Path in a Binary Tree Code
1var longestZigZag = function(root) {
2 let best = 0;
3 const dfs = (node, left, right) => {
4 if (node === null) {
5 return;
6 }
7 best = Math.max(best, left, right);
8 dfs(node.left, right + 1, 0);
9 dfs(node.right, 0, left + 1);
10 };
11 dfs(root, 0, 0);
12 return best;
13};

Longest ZigZag Path in a Binary Tree in Python, Java, C++, TypeScript and C

Longest ZigZag Path in a Binary Tree in Python
class Solution:
    def longestZigZag(self, root: Optional[TreeNode]) -> int:
        best = 0

        def dfs(node, left, right):
            nonlocal best
            if node is None:
                return
            best = max(best, left, right)
            dfs(node.left, right + 1, 0)
            dfs(node.right, 0, left + 1)

        dfs(root, 0, 0)
        return best
Longest ZigZag Path in a Binary Tree in Java
class Solution {
    private int best = 0;

    public int longestZigZag(TreeNode root) {
        dfs(root, 0, 0);
        return best;
    }

    private void dfs(TreeNode node, int left, int right) {
        if (node == null) {
            return;
        }
        best = Math.max(best, Math.max(left, right));
        dfs(node.left, right + 1, 0);
        dfs(node.right, 0, left + 1);
    }
}
Longest ZigZag Path in a Binary Tree in C++
class Solution {
    int best = 0;

    void dfs(TreeNode* node, int left, int right) {
        if (node == nullptr) {
            return;
        }
        best = max({best, left, right});
        dfs(node->left, right + 1, 0);
        dfs(node->right, 0, left + 1);
    }

public:
    int longestZigZag(TreeNode* root) {
        dfs(root, 0, 0);
        return best;
    }
};
Longest ZigZag Path in a Binary Tree in TypeScript
function longestZigZag(root: TreeNode | null): number {
    let best = 0;
    const dfs = (node: TreeNode | null, left: number, right: number): void => {
        if (node === null) {
            return;
        }
        best = Math.max(best, left, right);
        dfs(node.left, right + 1, 0);
        dfs(node.right, 0, left + 1);
    };
    dfs(root, 0, 0);
    return best;
}
Longest ZigZag Path in a Binary Tree in C
static int best;

static void dfs(struct TreeNode* node, int left, int right) {
    if (node == NULL) {
        return;
    }
    if (left > best) {
        best = left;
    }
    if (right > best) {
        best = right;
    }
    dfs(node->left, right + 1, 0);
    dfs(node->right, 0, left + 1);
}

int longestZigZag(struct TreeNode* root) {
    best = 0;
    dfs(root, 0, 0);
    return best;
}

Edge Cases & Common Mistakes

  • Counting nodes instead of edges: a single node is 0, not 1.
  • Mixing up the two lengths: the left child gets (right + 1, 0), not (left + 1, 0). A left step extends the path whose last step went right.
  • Only starting at the root: the longest zigzag can start anywhere; carrying both lengths down covers every start, because a broken zigzag restarts at length 1 on the next step.
  • Deep trees: up to 50,000 nodes can make the recursion deep; an explicit stack avoids a stack overflow.

Summary

DFS with two lengths per node: arriving by a left step and by a right step. The left child gets (right + 1, 0), the right child (0, left + 1), and the answer is the largest length seen. O(n) time, O(h) recursion space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start at the root

    Call dfs(root, 0, 0): no step has been taken yet.

  2. Update the best

    At each node, best = max(best, left, right).

  3. Pass the lengths down

    The left child gets (right + 1, 0); the right child gets (0, left + 1).

Frequently asked questions

What do the two numbers passed down mean?

`left` is the length of the zigzag that reached this node with a step to the left (the node is a left child on that path), and `right` the one that reached it with a step to the right. Either can be the end of the longest zigzag, so the answer is the largest of them over all nodes.


Why does the left child get (right + 1, 0)?

Stepping to the left child is a left step. It continues a zigzag only if the previous step was to the right, so the new left length is right + 1. A path that arrives by a left step cannot be extended by another left step, so the child’s right length starts over at 0 and grows from there. The right child gets (0, left + 1) by symmetry.


Is the length counted in nodes or edges?

Edges: a single node has length 0 and one step has length 1. That is why the root is called with (0, 0) and each step adds 1.


What is the brute-force approach?

From every node, walk a zigzag starting left and one starting right and keep the longest. Each walk can be O(h) long, so it is O(n · h): O(n²) on a degenerate tree. Passing the lengths down does it in one O(n) pass.

New to the technique behind this problem? Watch it run step by step:

Depth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description