3ms C++ self-explanatory solution


  • 0
    Y
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> res;
            helper(res,root,0);
            const int N(res.size());
            for(int i=1;i<N;i+=2){//reverse the even index row
                std::reverse(res[i].begin(),res[i].end());
            }
            return res;
        }
    private:
        void helper(vector<vector<int>> & res,TreeNode*root,int level){
            if(!root) return;
            if(level==res.size()){
                res.push_back(vector<int>());
            }
            res[level].push_back(root->val);
            helper(res,root->left,level+1);
            helper(res,root->right,level+1);
        }
    };
    

Log in to reply
 

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