Accepted C++ Solution


  • 0
    T
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> results;
            if(!root) return results;
            traverse(results, root, 0);
            
            for(int i=1; i<results.size(); i+=2){
                vector<int>* v = &results[i];
                std:reverse(v->begin(), v->end());
            }
            return results;
        }
        
        void traverse(vector<vector<int>>&results, TreeNode* root, int level){
            if(!root) return;
            if(level >= results.size()) results.push_back(vector<int>());
            results[level].push_back(root->val);
            traverse(results, root->left, level+1);
            traverse(results, root->right, level+1);
        }
    };
    

Log in to reply
 

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