Very naiiive 15-line cpp


  • 2
    M
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> ans;
            if (root==0) return ans;
            vector<TreeNode*> exp = {root};
            int p=0, dir=1;
            
            do {
                ans.push_back( vector<int>() );
                for(int i = dir==1 ? p : exp.size()-1; dir==1 ? i<exp.size() : i>=p; i+=dir)
                    ans.back().push_back(exp[i]->val);
                
                int end=exp.size()-1;
                for (int i=p; i<=end; i++) {
                    if (exp[i]->left!=0) exp.push_back(exp[i]->left);
                    if (exp[i]->right!=0) exp.push_back(exp[i]->right);
                }
                p = end+1;
                dir *= -1;
            } while (p<=exp.size()-1);
            return ans;
        }
    };

Log in to reply
 

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