Longest ZigZag Path in a Binary Tree

You are given the root of a binary tree.

A ZigZag path for a binary tree is defined as follows:

  • Choose any node in the binary tree and a direction, either right or left.
  • If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
  • Change the direction from right to left or from left to right.
  • Repeat the second and third steps until you cannot move in the tree.

The ZigZag length is defined as the number of nodes visited minus 1. A single node has a length of 0.

Return the longest ZigZag path contained in that tree.

Example 1
        1
         \
          1
         / \
        1   1
           / \
          1   1
           \
            1
             \
              1
Inputroot = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output3
The longest ZigZag path has length 3 following the directions right -> left -> right.
Example 2
        1
       / \
      1   1
       \
        1
       / \
      1   1
       \
        1
Inputroot = [1,1,1,null,1,null,null,1,1,null,1]
Output4
The longest ZigZag path has length 4 following the directions left -> right -> left -> right.

Constraints

  • The number of nodes in the tree is in the range [1, 5 * 10^4].
  • 1 <= Node.val <= 100

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate