首页 > 解决方案 > 运行时错误:引用绑定到向量类型的空指针

问题描述

在解决 leetcode 问题时,我遇到了参考错误。不知道为什么??

这里我不知道向量的维度。如果我给向量一些随机大小,那么这段代码不会给出任何错误。还有其他方法吗??

第 1034 行:字符 9:运行时错误:引用绑定到类型为“std::vector<int, std::allocator>”的空指针 (stl_vector.h) 摘要: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;
    }
};

标签: c++

解决方案


请尝试使用此代码,这将起作用。

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;
        
    }
};

推荐阅读