Skip to content
Problem 1372 · LeetCode 1372(opens in a new tab)

Longest ZigZag Path in a Binary Tree

MediumDepth-first search

You are handed a binary tree through its root. In it, a zigzag path starts at any node, takes one step to a child (left or right, your choice), and then keeps stepping down while switching sides every time: left, right, left, ... or right, left, right, ... It ends when the child it needs is missing.

The length of a zigzag path is the number of edges it uses, so a path that never moves has length 0. Return the length of the longest zigzag path anywhere in the tree.

Example 1

Input:  root = [1, 2, 3, null, 4, null, null, 5]
Output: 3
Why:    1 → 2 → 4 → 5 goes left, right, left
2 more examples and the constraints

Example 2

Input:  root = [6, null, 7, 8, 9]
Output: 2
Why:    6 → 7 goes right, then 7 → 8 goes left

Example 3

Input:  root = [4]
Output: 0
Why:    a lone node cannot move

Constraints

  • The tree holds between 1 and 50,000 nodes
  • Every node value is between 1 and 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Walk from every nodeO(n·h)
  2. DFS with two lengthsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 50,000-node zigzag chainVerdict
Walk from every nodeO(n·h)
Too slow on tall trees
DFS with two lengthsO(n)
Best; one visit per node

n = number of nodes, h = height of the tree (up to n).

Edge cases to test

  • A single node. [4] has no edges to walk, so the answer is 0.
  • A straight chain. A tree that only goes left can never turn, so the best path is one edge: 1.
  • The best path starts deep. The longest zigzag does not have to touch the root; every node must be allowed to start one.
  • A tall zigzag. A chain of 50,000 nodes that turns each step has answer 49,999 and recursion 50,000 deep; raise the limit or use an explicit stack in Python.

Common mistakes

  • Counting nodes instead of edges, which gives an answer one too high.
  • Only starting paths at the root, which misses zigzags lower in the tree.
  • Passing left + 1 to the left child, which rewards going the same way twice.

How to talk through it

  1. 1Clarify. Is the length counted in edges? Can the path start at any node, or only at the root?
  2. 2Give the simple version. From every node, walk a zigzag in both starting directions and keep the longest.
  3. 3Spot the repeated work. A walk from a parent contains the walk from its child, so carry lengths down instead of re-walking.
  4. 4Code the DFS. dfs(node, left, right): update best, then the left child gets (right + 1, 0) and the right child (0, left + 1).
  5. 5Test out loud. Run a single node, a straight chain and Example 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?