Runtime error for queue based iterative solution. Please help


  • 0
    T

    I get this output when I try to run this code. Last executed input: {0}

    I'm trying out similar to level order traversal here..

    Here's my 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) {
            /* Keep two queues, one current one auxiliary */
            queue<TreeLinkNode *>cur, aux;
            /* If we have atleast one element, push it into current queue */
            if(root != NULL)
                cur.push(root);
            /* Till the current queue doesn't become empty */
            while(!cur.empty()) {
                /* For this level */
                while(!cur.empty()) {
                    /* Pop the front element in the queue */
                    TreeLinkNode *node = cur.front();
                    cur.pop();
                    /* Push its children onto aux queue */
                    if(node->left)
                        aux.push(node->left);
                    if(node->right)
                        aux.push(node->right);
                    /* Peek at the next element, if not NULL make next point to it */
                    TreeLinkNode *temp = cur.front();
                    if(temp)
                        node->next = temp;
                }
                /* cur will be zero sized, aux would be full if populated, or zero if not */
                cur.swap(aux);
            }
        }
    };
    

    I tried running this on my laptop, runs without issues for 0, 1, 3 node trees.

    Any help, hints are appreciated. Thanks in advance.


Log in to reply
 

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