Longest ZigZag Path in a Binary Tree

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.

30:00

Longest ZigZag Path in a Binary Tree
medium
Free written solution
Topics
Companies

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.

Example 1:
Input: {"root":[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]}
Output: 3
Constraints:
  • The number of nodes in the tree is in the range [1,5×104][1, 5 \times 10^4].

  • 1≤Node.val≤1001 \leq \text{Node.val} \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]}

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)

Variables
VariableValue
node-
left-
right-
best0
stack1
DepthFunction Call
Stack empty
0/14