← Home

103. Binary Tree Zigzag Level Order Traversal

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
103

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 103. Binary Tree Zigzag Level Order Traversal, the solution in this repository is mainly a two pointers solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

The notes already sitting in the source point us in the right direction:

  • stack

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are level, dfs.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//stack
02//Runtime: 8 ms, faster than 36.00% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.
03//Memory Usage: 12.3 MB, less than 54.30% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13 * };
14 */
15class Solution {
16public:
17    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
18        vector<vector<int>> ans;
19        
20        if(!root) return ans;
21        
22        stack<TreeNode*> stk, stk_next;
23        TreeNode* cur;
24        bool pos = true;
25        
26        stk.push(root);
27        while(!stk.empty()){
28            int levelSize = stk.size();
29            vector<int> level(levelSize);
30            bool next_pos = !pos;
31            
32            for(int i = 0; i < levelSize; ++i){
33                cur = stk.top(); stk.pop();
34                level[i] = cur->val;
35                
36                TreeNode* child1 = cur->left;
37                TreeNode* child2 = cur->right;
38                
39                if(next_pos){
40                    /*
41                    if next_pos is true, we go from left to right,
42                    so right child should be pushed into stack earlier
43                    */
44                    swap(child1, child2);
45                }
46                
47                if(child1) stk_next.push(child1);
48                if(child2) stk_next.push(child2);
49                
50            }
51            
52            swap(stk, stk_next);
53            pos = next_pos;
54            ans.push_back(level);
55        }
56        
57        return ans;
58    }
59};
60
61//dfs
62//https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/33815/My-accepted-JAVA-solution
63//Runtime: 8 ms, faster than 36.00% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.
64//Memory Usage: 12.8 MB, less than 9.80% of C++ online submissions for Binary Tree Zigzag Level Order Traversal.
65/**
66 * Definition for a binary tree node.
67 * struct TreeNode {
68 *     int val;
69 *     TreeNode *left;
70 *     TreeNode *right;
71 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
72 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
73 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
74 * };
75 */
76class Solution {
77public:
78    void dfs(TreeNode* cur, int level, vector<vector<int>>& ans){
79        if(!cur) return;
80        
81        if(ans.size() == level){
82            //in level 0, we totally have 1 level
83            ans.push_back(vector<int>());
84        }
85        
86        /*
87        the only difference is that 
88        we build the ans from left to right or
89        from right to left
90        */
91        if(!(level&1)){
92            //level is even
93            //in current level, we go from left to right
94            ans[level].push_back(cur->val);
95        }else{
96            ans[level].insert(ans[level].begin(), cur->val);
97        }
98        
99        //we still visit the tree from left to right
100        dfs(cur->left, level+1, ans);
101        dfs(cur->right, level+1, ans);
102    };
103    
104    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
105        vector<vector<int>> ans;
106        
107        dfs(root, 0, ans);
108        
109        return ans;
110    }
111};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.