My code is not right, but why is it accepted?


  • 0
    Z

    My code simply goes to each level of the tree, stores each node in a sequence and connects them.
    It uses O(N) space, but is still accepted.

      void connect(TreeLinkNode *root) {
        	if (root == NULL){
    	        return;
            }
        	vector<TreeLinkNode*> curLevel;
        	vector<TreeLinkNode*> nextLevel;
        	curLevel.push_back(root);
        	while (!curLevel.empty()){
        		for (int i = 0; i < curLevel.size() - 1; i++){
        			curLevel[i] -> next = curLevel[i + 1];
        
        			if (curLevel[i]->left != NULL){
        				nextLevel.push_back(curLevel[i]->left);
        			}
        
        			if (curLevel[i]->right != NULL){
        				nextLevel.push_back(curLevel[i]->right);
        			}
        		}
        		TreeLinkNode * last = curLevel[curLevel.size() - 1];
        		last -> next = NULL;
        		if (last->left != NULL){
        			nextLevel.push_back(last->left);
        		}
        
        		if (last->right != NULL){
        			nextLevel.push_back(last->right);
        		}
        		curLevel = nextLevel;
        		nextLevel.clear();
        	}
    }

  • 0

    What do you mean it's not right?

    1. If you meant code correctness, please suggest a test case which your code produces the wrong answer but still got accepted.

    2. If you meant extra space, the judger currently does not enforce that.


Log in to reply
 

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