Easy-to-understand c++ solution by bfs, 4ms


  • 2
    S
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> ans;
            if(!root)  return ans;
            vector<int> numbers;
            queue<TreeNode*> q;
            q.push(root);
            int num = 1,lineNum = 1;
            vector<int> tmp;
            while(!q.empty()){
                TreeNode* p = q.front();
                tmp.push_back(p->val);
                q.pop();
                if(p->left!=NULL)  q.push(p->left);
                if(p->right!=NULL)  q.push(p->right);
                num--;
                if(num <= 0){
                    if(lineNum % 2 == 0)
                        reverse(tmp.begin(),tmp.end());
                    ans.push_back(tmp);
                    num = q.size();
                    lineNum++;
                    tmp.clear();
                }
            }
            return ans;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.