




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.
    
This C solution uses a queue to perform a level order traversal of the tree. It maintains an array of lists, where each list contains values of nodes at the same level. We also keep track of the direction using the level number: odd levels are reversed using an auxiliary reverse function. This solution balances both clarity and 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.
1#include <iostream>
2#include <vector>
3using namespace std;
4
5struct TreeNode {
6    int val;
7    TreeNode *left;
8    TreeNode *right;
9    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10};
11
12class Solution {
13public:
14    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
15        vector<vector<int>> res;
16        dfs(root, 0, res);
17        return res;
18    }
19
20private:
21    void dfs(TreeNode* node, int depth, vector<vector<int>>& res) {
22        if (node == NULL) return;
23        if (depth >= res.size()) {
24            res.push_back(vector<int>());
25        }
26        if (depth % 2 == 0) {
27            res[depth].push_back(node->val);
28        } else {
29            res[depth].insert(res[depth].begin(), node->val);
30        }
31        dfs(node->left, depth + 1, res);
32        dfs(node->right, depth + 1, res);
33    }
34};Using C++, this solution leverages DFS with depth-based bookkeeping to form the zigzag pattern. Collections for each level are managed with insertions according to depth, and recursion handles tree traversal seamlessly.