Longest ZigZag Path in a Binary Tree solution explained

To find the longest zigzag path in a binary tree, walk the tree once and give every node two numbers: the length of the zigzag that reaches it with a left move and the length that reaches it with a right move. A left child extends its parent's right-move count by one, a right child extends the parent's left-move count, and the other count restarts at zero. The largest number seen is the answer, in O(n) time and O(h) space.

By Published 8 min read

Understanding the task

A zigzag path starts at any node of a binary tree. You choose a first direction, left or right, and move to that child. After that, every move must go the opposite way from the previous one: left, right, left, and so on, or right, left, right. You may stop at any point, and you must stop when the child you need does not exist. The length of the path is the number of moves, that is, edges. Return the longest length possible anywhere in the tree.

          1
         / \
        2   8
       /
      3
       \
        4
       /
      5
       \
        6

Best path: 2 -> 3 (left) -> 4 (right) -> 5 (left) -> 6 (right)
Answer: 4 edges
A tree drawn for this page

The root does not lead the way here. Starting at 1 and going left reaches 2, but 2 has no right child, so that path ends after one edge. The best path begins one level down. A single node has a zigzag of length 0, and a tree where every node only has a left child has an answer of 1, since the second move would need a right child.

What it tests

The problem checks whether you can define the right state for a tree walk. Knowing a node's depth or a single path length is not enough, because what a child can do next depends on how the path reached its parent. Candidates who pin that down in a sentence usually finish quickly; candidates who start coding with one counter tend to get tangled. Common follow-up questions:

  • Count nodes instead of edges. Add one to the final answer, and confirm the empty-tree case.
  • Return the path. Remember where each best count started, or record the node where the maximum ended and rebuild by walking upward with parent links.
  • Paths must start at the root. Then only the root's two directions matter, and the brute force is already linear.
  • Weighted zigzags. Each edge carries a weight; carry sums instead of counts.
  • Very deep trees. Use an explicit stack, as in the JavaScript version below.

Brute force: walk it from every start

Here is a helpful observation: once you fix the starting node and the first direction, there is no choice left. Every later move is forced. So the brute force tries each node with each first direction and simply follows the path until it runs out, keeping the longest. Each walk is at most h steps long and there are 2n walks, so the total is O(n·h), which becomes O(n²) on a tree shaped like the example stretched out.

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

def longest_zigzag_brute(root):
    best = 0
    stack = [root] if root else []
    while stack:
        node = stack.pop()
        for go_left in (True, False):
            cur, steps, left = node, 0, go_left
            while True:
                nxt = cur.left if left else cur.right
                if nxt is None:
                    break
                cur, steps, left = nxt, steps + 1, not left
            best = max(best, steps)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return best
Python: follow the forced path from every node and both directions. O(n·h). Test reference.

Linear solution: two counts per node

Look at the walks the brute force repeats. The path 2, 3, 4, 5, 6 and the path 3, 4, 5, 6 share their whole tail. Instead of restarting from each node, carry the progress downward. For each node keep two numbers: via_left, the longest zigzag that ends at this node with a left move, and via_right, the longest that ends here with a right move. The root has 0 for both.

Now the rules. Moving to the left child is a left move, so it can only extend a path whose last move was right: the child's via_left is the parent's via_right plus one. The child cannot be reached by a right move, so its via_right is 0, which also means "a new path could start here". The right child mirrors this: its via_right is the parent's via_left plus one and its via_left is 0. Track the maximum of all these numbers as you go.

def longest_zigzag(root):
    best = 0

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

    walk(root, 0, 0)
    return best
Python: recursive top-down DFS with two counters. O(n) time, O(h) stack.

Python's default recursion limit, about a thousand frames, will stop this version on a deep tree, which is exactly the kind of tree where zigzags get long. The JavaScript version keeps the same triple of node and two counters on an explicit stack, so depth no longer matters.

function longestZigZag(root) {
  let best = 0;
  if (root === null) return best;
  const stack = [[root, 0, 0]];
  while (stack.length > 0) {
    const [node, viaLeft, viaRight] = stack.pop();
    if (viaLeft > best) best = viaLeft;
    if (viaRight > best) best = viaRight;
    if (node.left !== null) stack.push([node.left, viaRight + 1, 0]);
    if (node.right !== null) stack.push([node.right, 0, viaLeft + 1]);
  }
  return best;
}
JavaScript: the same counters on an explicit stack. O(n) time, O(h) to O(n) stack.

Trace the example. Root 1 starts with (0, 0). Its left child 2 gets (1, 0), and 8 gets (0, 1). Node 3, a left child of 2, gets via_left = 0 + 1 = 1, a fresh start from 2. Node 4, a right child, gets via_right = 1 + 1 = 2. Node 5 gets via_left = 3, and node 6 gets via_right = 4. The maximum is 4.

A bottom-up version also works: each node returns how far a zigzag can go if it starts there heading left and heading right, computed from its children's opposite values. Both are O(n). The top-down form is a little shorter and matches how the path is described, so it is the easier one to explain.

Complexity

n nodes, height h
ApproachTimeExtra space
Walk the forced path from every node, both directionsO(n·h), O(n²) worst caseO(n) for the node stack
Top-down counters, recursiveO(n)O(h) call stack
Top-down counters, explicit stackO(n)O(h) to O(n) for the stack
Bottom-up (start-left, start-right) per nodeO(n)O(h) call stack
n nodes, height h. Scroll sideways on a small screen.

Edge cases

  • One node: 0.
  • A chain that only goes left (or only right): 1.
  • A perfect zigzag chain of n nodes: n - 1, and a good depth test.
  • The best path starting below the root, as in the example.
  • A perfect tree of height h: you can alternate all the way from the root to the bottom, so the answer is h.

Where people go wrong

  • Giving the child via_left = parent's via_left + 1 for a left move, which counts two left moves in a row.
  • Resetting the other counter to -1 or forgetting to reset it, which breaks the fresh start at that node.
  • Counting nodes rather than edges and returning one too many.
  • Only starting paths at the root.
  • Updating the answer only at leaves. A zigzag can end at an inner node whose only child is on the wrong side: 1, then right to 2, then left to 3, where 3 has only a left child, is 2 edges long, but the leaf below 3 only sees a count of 1.

How to explain it out loud

Fictional example

Defining the state first
Candidate
What a child can do depends on the last move into its parent, so I will carry two numbers: the zigzag length arriving here by a left move, and by a right move.
Candidate
Going left extends the right-move count by one. The other count goes to zero, which also covers starting a new path at that child.
Interviewer
Do you need to restart from each node?
Candidate
No, the zero reset handles new starts, so one pass is enough. It is O(n) time, and I can use a stack if the tree is deep.

Diameter of N-ary Tree is another longest-path problem where the best path need not touch the root. Pseudo-Palindromic Paths in a Binary Tree also carries state from parent to child, as a bitmask. House Robber IV shows a different rule about neighbors driving a solution, and Vertical Order Traversal tracks left and right moves as column offsets.

Using Natively while you prepare

During practice on Mac or Windows, Natively can read the zigzag problem from a screenshot and show an approach and code in its overlay. It is also useful for a narrow check, such as asking why the opposite counter resets to zero, without getting a full solution. Transcribe a spoken mock round with it and you can see afterward whether your state definition came out clearly. See the AI interview assistant.

Questions people ask

How do you find the longest zigzag path in a binary tree?

Walk the tree with two counts per node: the zigzag length arriving by a left move and by a right move. A left child gets the parent's right count plus one, a right child gets the left count plus one, and the other count resets to zero.

Can the longest zigzag path start below the root?

Yes. The path may start at any node, and resetting the opposite counter to zero is what lets a new path begin at each node in the same pass.

What is the time complexity of Longest ZigZag Path in a Binary Tree?

O(n) time, since each node is visited once with constant work, and O(h) extra space for the recursion or stack.

Is the zigzag length counted in nodes or edges?

In edges, so a single node has length 0 and a parent with one child has length 1.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP