Longest ZigZag Path in a Binary Tree
Problem Statement
You are given the root of a binary tree.
A zigzag path starts at any node. Its moves alternate: a move to the left child, then a move to the right child, then left again, and so on. The first move can be either way. The length of the path is the number of moves. A single node has length 0. Return the length of the longest zigzag path in the tree.
The root of a binary tree. It has at least one node.
The number of moves in the longest zigzag path.
The longest zigzag goes right, then left, then right. That is 3 moves.
The longest zigzag goes left, right, left, right. That is 4 moves.
A single node has no moves.
- • The tree has between 1 and 5 × 10^4 nodes.
- • 1 ≤ Node.val ≤ 100
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
From each node, follow the zigzag in both first directions and keep the longest walk
Pass down (length if the last move was left, length if it was right); both update at each child
For every node and each first direction, walk down while the moves keep alternating, and stop when the child is missing. Count the moves. Do this for every node, and keep the biggest count.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.