My BFS cpp code


  • 0
    C
    class Solution {
    public:
        void connect(TreeLinkNode *root)
        {
            if(!root) return;
            
            queue<TreeLinkNode*> q;
            q.push(root);
            
            while( !q.empty() )
            {
                int qsize = q.size();
                
                TreeLinkNode *prev = NULL;
                while(qsize--)
                {
                    TreeLinkNode *node = q.front();
                    q.pop();
                    
                    node->next = prev;
                    
                    if(node->right) q.push(node->right);
                    if(node->left)  q.push(node->left);
                    
                    prev = node;
                }
            }
        }
    };

Log in to reply
 

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