Why this code's result is incorrect?


  • 0
    F

    Input : [3,9,20,null,null,15,7]
    My Output : [[3],[20,9],[15,7],[],[]]
    Expected: [[3],[20,9],[15,7]].

     class Solution {
     public:
         vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
             vector<vector<int>> ret;
             zigzagTraversal(root,0,false,ret);
             return ret;
         }
         void zigzagTraversal(TreeNode* root,int level,bool zig,vector<vector<int>> &ret){
             if(!root)
                 return;
             if(level==ret.size());
                 ret.push_back({});
             if(zig)
                 ret[level].insert(ret[level].begin(),root->val);
             else
                 ret[level].push_back(root->val);
             zigzagTraversal(root->left,level+1,!zig,ret);
             zigzagTraversal(root->right,level+1,!zig,ret);
         }
     };
    

Log in to reply
 

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