C++ solution using queue and vector.insert function for odd levels


  • 0
    S
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
           queue<TreeNode*> q;
            queue<int> qLevel;
            vector<vector<int>> v;
            if(root==NULL){
                return v;
            }
            q.push(root);
            qLevel.push(0);
            while(!q.empty()){
                TreeNode *temp = new TreeNode(0);
                temp=q.front();
                q.pop();
                int level=qLevel.front();
                qLevel.pop();
                if(level>=v.size()){
                    vector<int> vTemp;
                    vTemp.push_back(temp->val);
                    v.push_back(vTemp);
                }else{
                    if(level%2==0){
                        v[level].push_back(temp->val);
                    }else{
                        v[level].insert(v[level].begin(),temp->val);
                    }
                }
                if(temp->left!=NULL){
                    q.push(temp->left);
                    qLevel.push(level+1);
                }
                if(temp->right!=NULL){
                    q.push(temp->right);
                    qLevel.push(level+1);
                }
            }
            return v; 
        }
    

Log in to reply
 

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