




Sponsored
Sponsored
This approach leverages the standard Breadth-First Search (BFS) algorithm to perform a level order traversal. We use a queue to traverse the tree level-by-level. For each level, we determine the order (left-to-right or right-to-left) by toggling a flag. At odd levels, we simply reverse the order of elements collected from the queue to achieve the zigzag effect.
Time Complexity: O(n), where n is the number of nodes in the tree, as each node is processed once.
Space Complexity: O(n), for storing the output and additional structures, like the queue used for BFS.
1var zigzagLevelOrder = function(root) {
2    if (!root) return [];
3
4    const result = [];
5    const queue = [root];
6    let leftToRight = true;
7
8    while (queue.length > 0) {
9        const size = queue.length;
10        const levelNodes = [];
11
12        for (let i = 0; i < size; i++) {
13            const node = queue.shift();
14            if (leftToRight) {
15                levelNodes.push(node.val);
16            } else {
17                levelNodes.unshift(node.val);
18            }
19
20            if (node.left) queue.push(node.left);
21            if (node.right) queue.push(node.right);
22        }
23
24        result.push(levelNodes);
25        leftToRight = !leftToRight;
26    }
27
28    return result;
29};In this JavaScript solution, we utilize an array as a queue for BFS traversal. By adjusting the position of node insertion based on the direction toggle (leftToRight), we efficiently produce the zigzag output pattern.
In contrast to the BFS method, this approach utilizes Depth-First Search (DFS) for traversal. Recursive calls are made to process each node, and a hashmap (or similar structure) tracks the current depth. Depending on the depth, nodes are appended to the left or right of the current level list. This achieves the zigzag pattern as the recursion progresses.
Time Complexity: O(n), as DFS visits each node once.
Space Complexity: O(n), considering both storage needs for recursive calls and the result list.
Java utilizes a LinkedList for flexible insertions (both ends) to manage depth-called reversals. Recursion affords the processing of each node, ensuring the zigzag is applied through pre-determined level indexing.