Problem 37 of 75

Longest ZigZag Path in a Binary Tree

MediumNot solved yetInterview me on this
Before you code · which pattern fits?

The problem

A ZigZag path starts at any node, moves to a child, then keeps alternating direction (left, right, left, …). The length is the number of nodes visited − 1. Given the root of a binary tree, return the longest ZigZag path length.

[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1] → 3 [1,1,1,null,1,null,null,1,1,null,1] → 4

Your solution runs against 3 unit tests, including edge and large-value cases.

Loading...

Test console · 3 unit tests

Submit your code to run it against all 3 unit tests. Results appear here.

JavaScript, TypeScript & Python run sandboxed in your browser; other languages run on the execution server. Your code is saved locally as you type.

Hint

Reference solution

Video explanation

Longest ZigZag Path in a Binary Tree, explainedcodestorywithMIK