My accepted but not perfect solution


  • 0
    E

    class Solution {
    public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector< vector<int> > res;

        if(!root) return res;
        int h = height(root);
        for(int i = 1;i<=h;i++){
            vector<int> v;
            traverse(root,i,v);
            res.push_back(v);
        }
        if(res.size()==1) return res;
        for(int i=1;i<res.size();i=i+2){
            reverse(res[i].begin(),res[i].end());
        }
        return res;
    }
    void traverse(TreeNode*root, int height,vector<int>& v){
        if(!root)
            return;
        if(height==1){
            v.push_back(root->val);
        }
        else if(height>1){
            traverse(root->left,height-1,v);
            traverse(root->right,height-1,v);
        }
    }
    int height(TreeNode* root){
        if(!root) return 0;
        return(std::max(height(root->left),height(root->right)))+1;
    }
    

    };


Log in to reply
 

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