c++ - 运行时错误:引用绑定到向量类型的空指针
问题描述
在解决 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;
}
};
解决方案
请尝试使用此代码,这将起作用。
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;
}
};
推荐阅读
- reactjs - 单个网页上的多个反应应用程序的多个 redux 实例
- java - 扩展 Serializable Interface 的 POJO 类也称为 POJO 类?
- html - Flexbox / Bootstrap 4 - 将元素拉伸到父元素的剩余高度
- ios - 快速从表视图问题中搜索动态数据问题
- google-sheets - Google 表格 - 通过 importrange 链接并插入新行
- android - 为底部导航栏设置选中和未选中状态不起作用 [Android]
- xml - 每个不工作的 xslt
- android - 将视图添加到 flexboxlayout
- scala - Kafka Spark Stream 直接保存到 Redis
- rx-java - Spring boot graphql-java,订阅和流监听器