Loading content...
You are given the root of a binary tree. Your task is to return a wave-like level order traversal of the tree's node values. In this traversal pattern, you process the tree level by level, but the direction of traversal alternates at each level:
This creates a serpentine or wave pattern where the traversal direction "bounces" back and forth like a pendulum swinging between the sides of the tree.
Return the result as a 2D array where each inner array contains the node values at that level in the specified traversal order. If the tree is empty (root is null), return an empty array.
root = [3,9,20,null,null,15,7][[3],[20,9],[15,7]]Level 0: We traverse left to right, yielding [3]. Level 1: We traverse right to left, so we get [20, 9] (not [9, 20]). Level 2: We traverse left to right again, yielding [15, 7]. The wave pattern creates the serpentine order [[3],[20,9],[15,7]].
root = [1][[1]]The tree contains only the root node with value 1. Since there's only one level, we simply return [[1]].
root = [][]An empty tree has no nodes to traverse, so we return an empty array.
Constraints