简体   繁体   中英

runtime error: Reference binding to null pointer of type vector

while I was solving leetcode problem, I was getting reference error. Don't know why??

Here I don't know dimension of vector. If i give some random size to the vector then this code is not giving any error. Is there any other way of doing it??

Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator>' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* node) {
        vector<vector<int>> ans(4,vector<int>(4));
        queue<TreeNode *> q;
        q.push(node);
        q.push(NULL);
        int row = 0;
        int col = 0;
        while(q.empty() == false){
            TreeNode * temp = q.front();
            if(temp == NULL){

                if(q.size() > 1){
                    q.push(temp);
                    row++;
                    col = 0;
                }

            }
            else{
                ans[row][col] = node->val;
                if(temp->left != NULL){
                    q.push(temp->left);
                }
                if(temp->right != NULL){
                    q.push(temp->right);
                }
            }
            q.pop();
        }
        return ans;
    }
};

Try this code instead, this will work.

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if(root== NULL) return ans;
        
        queue<TreeNode*> q;
        q.push(root);
        
        while(!q.empty()){
            int size= q.size();
            vector<int> level;
            for(int i=0; i<size; i++){   
                TreeNode* node= q.front();
                q.pop();
                
                level.push_back(node->val);
                
                if(node->left != nullptr) q.push(node->left);
                if(node->right != nullptr) q.push(node->right);   
            }
            ans.push_back(level);
        }
        
        return ans;
        
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM