Run time error for level order traversal, gives correct input in local tests


  • 0
    S
    #include<iostream>
    #include<vector>
    #include<queue>
    #include<algorithm>
    
    using namespace std;
    
    struct TreeNode {
    	int val;
    	TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
     
    
    class Solution {
    public:
    	vector<vector<int> >& levelOrder(TreeNode* root) {
    	    vector<vector<int> > v1;
    		vector<int> v;
    		if(root == NULL)
    			return v1;
    
    	    queue<TreeNode*> q;
    	    q.push(root);
    	    q.push(NULL);
    	    while(!q.empty()) {
    	        TreeNode* t = q.front();
    	        q.pop();
    	        if(t == NULL) {
    					if(!q.empty()) {
    						v1.push_back(v);
    						q.push(NULL);
    						v.clear();
    				}
    	        }
    	        if(t !=NULL) {
    				v.push_back(t->val);
    				if(t->left != NULL) {
    					q.push(t->left);
    				}
    				if(t->right !=NULL) {
    					q.push(t->right);
    				}
    	        }
    	    }
    		v1.push_back(v);
    		return v1;
    	}
    };

  • 0
    S

    Wrong to return a ref of local vector, hence error


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.