A ZigZag path starts at any node, picks a direction (left or right), and moves to that child; after each move it switches direction and moves again, until the child it needs does not exist. Its length is the number of nodes visited minus one, so a single node has length 0. Given the root of a binary tree, return the length of its longest ZigZag path.
A ZigZag path starts at any node, picks a direction (left or right), and moves to that child; after each move it switches direction and moves again, until the child it needs does not exist. Its length is the number of nodes visited minus one, so a single node has length 0. Given the root of a binary tree, return the length of its longest ZigZag path.
Each node carries two numbers: left = length of the zigzag that reaches it by a left move, right = the one that reaches it by a right move. The root starts at (0, 0).
best
0
current node
-
11111111
stack (node, left, right)
(1, 0, 0)
← top
badge = left|rightleft edgeright edgezigzag ending at currentbest zigzag
left child: (right + 1, 0) right child: (0, left + 1)