




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.
The Python solution uses deque for both the queue and level list operations to efficiently achieve the zigzag pattern. The toggle mechanism allows levels to be appended left-to-right or right-to-left without compromising on runtime efficiency.
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.
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        dfs(root, 0, results);
15        return results;
16    }
17
18    private void dfs(TreeNode node, int depth, IList<IList<int>> results) {
19        if (node == null) return;
20
21        if (results.Count == depth) {
22            results.Add(new List<int>());
23        }
24
25        if (depth % 2 == 0) {
26            results[depth].Add(node.val);
27        } else {
28            results[depth].Insert(0, node.val);
29        }
30
31        dfs(node.left, depth + 1, results);
32        dfs(node.right, depth + 1, results);
33    }
34}This C# solution applies DFS with tracking of an element's depth to insert values either at the front or back of the list depending on the zigzag direction required, which alternates every level.