4ms c++ solution


  • 0
    I
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> curLevel;
        if (!root) return res;
        int rollIdx = 0;
        stack<TreeNode*> stck[2];
        stck[0].push(root);
        while (!stck[0].empty() || !stck[1].empty()) {
    	    TreeNode *cur = stck[rollIdx].top();
    	    curLevel.push_back(cur->val);
    	    stck[rollIdx].pop();
    	    if (rollIdx == 0) {
    		    if (cur->left) stck[1 - rollIdx].push(cur->left);
    		    if (cur->right) stck[1 - rollIdx].push(cur->right);
    	    } else {
    		    if (cur->right) stck[1 - rollIdx].push(cur->right);
    		    if (cur->left) stck[1 - rollIdx].push(cur->left);
    	    }
    	    if (stck[rollIdx].empty()) {
    		    res.push_back(curLevel);
    		    curLevel.clear();
    		    rollIdx = 1 - rollIdx;
    	    }
        }
        return res;
    }

Log in to reply
 

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