1

while I was solving leetcode problem, I was getting reference error. Don't know why??

Here I don't know dimension of vector. If i give some random size to the vector then this code is not giving any error. Is there any other way of doing it??

Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator>' (stl_vector.h) SUMMARY: 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;
    }
};

1 Answer 1

-1

Try this code instead, this will work.

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;
        
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please add some explanation of where this code differs from the asker's original code and why the change addresses their problem?
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.