Problem
You get the root of a binary tree. The input shows the tree as a list in level order. This order lists the nodes one level at a time, from left to right. A null value marks a missing child.
A zigzag path starts at any node and moves down the tree. For the first move, choose a direction, left or right, and move to that child. After each move, use the other direction for the next move. Stop when the next child does not exist.
The length of a zigzag path is the number of moves. This number is the number of nodes in the path minus 1. A path with only one node has the length 0.
Return the length of the longest zigzag path in the tree.
Example 1
- Input:
- root = [1,2,3,null,4,null,null,5]
- Output:
- 3
- Explanation:
- The path moves left from 1 to 2, right from 2 to 4, and left from 4 to 5.
Example 2
- Input:
- root = [1,2,null,3,null,null,4,5]
- Output:
- 3
- Explanation:
- The longest path starts at node 2, not at the root. It moves left to 3, right to 4 and left to 5.
Example 3
- Input:
- root = [4]
- Output:
- 0
Constraints
- 1 <= number of nodes <= 5 * 10^4
- 1 <= Node.val <= 100
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
- Path In Zigzag Labelled Binary Tree
Coding
- Binary Tree Longest Consecutive Sequence
Coding
- Binary Tree Longest Consecutive Sequence II
Coding
- Binary Tree Maximum Path Sum
Coding · Binary Tree · Depth-First Search · DP on Trees
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 1 record
No company association
Leetcode 1372. Longest ZigZag Path in a Binary Tree
Reported date not specified · 0 source reports
Source snapshot: Nov 12, 2026
View source