Straightforward C++ solution


  • 0
    K
    class Solution {
    public:
        void connect(TreeLinkNode *root) 
        {
            if(root==nullptr)
                return;
            
            queue<TreeLinkNode*> q;
            q.push(root);
            
            while(!q.empty())
            {
                int n = q.size();
                vector<TreeLinkNode*> temp;
                while(n--)
                {
                    TreeLinkNode* frontNode = q.front();
                    q.pop();
                    temp.push_back(frontNode);
                    if(frontNode->left)
                        q.push(frontNode->left);
                    if(frontNode->right)
                        q.push(frontNode->right);
                }
                for(auto i: temp) cout << i << " ";
                cout << endl;
                
                for(int i = 0; i < temp.size() - 1; i++)
                {
                    TreeLinkNode* currNode = temp[i];
                    currNode->next = temp[i+1];
                }
            }
            
        }
    };
    

    Simple level order traversal followed by creating a link list from the nodes.


Log in to reply
 

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