【发布时间】:2021-01-05 10:50:47
【问题描述】:
这是一个leetcode问题,我必须找出二叉树的右侧视图;
代码如下
错误:第 22 行:字符 37:运行时错误:“TreeNode”类型的空指针内的成员访问; (解决方案.CPP)
我无法确定在哪种情况下我正在尝试访问 NULL 的成员
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> v;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int count = q.size();
for(int i=count;i>0;i--){
if(i==1){
v.push_back(q.front()->val);//getting error in this line
}
if(q.front()->left){
q.push(q.front()->left);
}
if(q.front()->right){
q.push(q.front()->right);
}
q.pop();
}
}
return v;
}
};
【问题讨论】:
-
q.front()?调试器说什么? -
如果根为NULL怎么办?
-
感谢您的提及,这就是错误背后的真正原因,我添加了一个检查 root 是否为 NULL 的条件,然后它就起作用了
标签: c++ data-structures tree runtime-error