Why "delete pre;" doesn't AC ?


  • 0
    X

    This the AC version code

    /**
     * Definition for binary tree with next pointer.
     * struct TreeLinkNode {
     *  int val;
     *  TreeLinkNode *left, *right, *next;
     *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            	if (!root) return;
    			deque<TreeLinkNode *> curr, next;
    			curr.push_back(root);
    			while ( !curr.empty() )
    			{
    				TreeLinkNode *pre = new TreeLinkNode(0);
    				while ( !curr.empty() )
    				{
    					TreeLinkNode *tmp = curr.front(); curr.pop_front();
    					pre->next = tmp;
    					if (tmp->left) next.push_back(tmp->left);
    					if (tmp->right) next.push_back(tmp->right);
    					pre = tmp;
    				}
    				pre->next = NULL;
    				//delete pre;
    				std::swap(curr, next);
    			}
        }
    };
    

    This is the Runtime Error version code

    /**
     * Definition for binary tree with next pointer.
     * struct TreeLinkNode {
     *  int val;
     *  TreeLinkNode *left, *right, *next;
     *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            	if (!root) return;
    			deque<TreeLinkNode *> curr, next;
    			curr.push_back(root);
    			while ( !curr.empty() )
    			{
    				TreeLinkNode *pre = new TreeLinkNode(0);
    				while ( !curr.empty() )
    				{
    					TreeLinkNode *tmp = curr.front(); curr.pop_front();
    					pre->next = tmp;
    					if (tmp->left) next.push_back(tmp->left);
    					if (tmp->right) next.push_back(tmp->right);
    					pre = tmp;
    				}
    				pre->next = NULL;
    				delete pre;
    				std::swap(curr, next);
    			}
        }
    };
    

    The only difference is that Runtime Error version code has "delete pre;"
    I can not figure out why this line doesn't pass AC?
    Can any one give me some hints?


Log in to reply
 

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