Search code examples
c++data-structurestreeruntime-error

runtime error: member access within null pointer of type 'TreeNode'


Its a leetcode question in which I have to find out the right side view of the binary-tree;

the code is as follows

ERROR:Line 22: Char 37: runtime error: member access within null pointer of type 'TreeNode' ; (solution.CPP)

I am unable to find out in which case I am trying to access members of a 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;
    }
};

Solution

  • I think in this problem the root can be null also, so when the root is null then it will give this error. This is the case I think.

    use this

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