40ms C++ Solution using 2 queues


  • 0
    H
    class Solution {
    public:
    void connect(TreeLinkNode *root) {
        if(root != NULL){
        queue<TreeLinkNode*> q1;
        queue<TreeLinkNode*> q2;
        q1.push(root);
        int next_queue = 2;
        
        while(!q1.empty() || !q2.empty() ){
            if(next_queue == 2){
                TreeLinkNode * pre = NULL;
                while(!q1.empty()){
                    if(q1.front()->right != NULL){
                        q2.push(q1.front()->right);
                    }
                    
                    if(q1.front()->left != NULL){
                        q2.push(q1.front()->left);
                    }
                    q1.front()->next = pre; 
                    pre = q1.front();
                    q1.pop();
                   
                }
                next_queue = 1;
            }else{
                TreeLinkNode * pre = NULL;
                  while(!q2.empty()){
                     if(q2.front()->right != NULL){
                        q1.push(q2.front()->right);
                    }
                    if(q2.front()->left != NULL){
                        q1.push(q2.front()->left);
                    }
                    
                    
                    q2.front()->next = pre; 
                    pre = q2.front();
                    q2.pop();
                    
                }
                next_queue = 2;
            }
            
        }
        
    }
    }
    };

Log in to reply
 

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