




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.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5    public int val;
6    public TreeNode left;
7    public TreeNode right;
8    public TreeNode(int x) { val = x; }
9}
10
11public class Solution {
12    public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
13        IList<IList<int>> results = new List<IList<int>>();
14        if (root == null) return results;
15
16        Queue<TreeNode> queue = new Queue<TreeNode>();
17        queue.Enqueue(root);
18        bool leftToRight = true;
19
20        while (queue.Count > 0) {
21            int size = queue.Count;
22            LinkedList<int> levelNodes = new LinkedList<int>();
23            for (int i = 0; i < size; i++) {
24                var node = queue.Dequeue();
25                if (leftToRight) {
26                    levelNodes.AddLast(node.val);
27                } else {
28                    levelNodes.AddFirst(node.val);
29                }
30
31                if (node.left != null) queue.Enqueue(node.left);
32                if (node.right != null) queue.Enqueue(node.right);
33            }
34            results.Add(new List<int>(levelNodes));
35            leftToRight = !leftToRight;
36        }
37        return results;
38    }
39}The C# solution adopts a queue to traverse level-by-level. Using a LinkedList for level nodes supports efficient insertion at both ends, achieving the zigzag pattern by switching from left-to-right to right-to-left order every level.
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.
This JavaScript DFS implementation recursively manipulates a result array, inserting at either the start or end of each level array according to current depth parity. Recursive calls facilitate the traversal.