【问题标题】:runtime error: member access within null pointer of type 'TreeNode' [closed]运行时错误:“TreeNode”类型的空指针内的成员访问[关闭]
【发布时间】: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


【解决方案1】:

我认为在这个问题中root 也可以为空,所以当root 为空时,它会给出这个错误。我认为是这样的。

使用这个

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> v;
        if(root == null) return 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;
    }
};

【讨论】:

  • 这是出现错误的原因,谢谢提及
猜你喜欢
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 1970-01-01
相关资源
最近更新 更多