1. Standard BFS Level Order with Array Reverse
Intuition
Run standard BFS level-order traversal. For every odd level (index 1, 3, 5...), call reverse() on that level's array.
When to apply: Basic baseline check.
Algorithm
- Step 1: Perform standard BFS level order traversal into result array of arrays.
- Step 2: Loop through result: if i % 2 == 1, reverse result[i].
- Step 3: Return result.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { if (!root) return {}; vector<vector<int>> res; queue<TreeNode*> q; q.push(root); int lvl = 0; while (!q.empty()) { int sz = q.size(); vector<int> cur; for (int i = 0; i < sz; ++i) { TreeNode* node = q.front(); q.pop(); cur.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } if (lvl % 2 == 1) reverse(cur.begin(), cur.end()); res.push_back(cur); lvl++; } return res; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Each node visited once, plus reversing elements takes O(n) total. - Space complexity:
O(w)— Queue holds maximum width of tree w.