A queue based solution in C++, even works for non-perfect tree,


  • 1
    D
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(!root) return;
            queue<TreeLinkNode *> q;
            q.push(root);
            TreeLinkNode *tmp;
            int qsz;
            while(!q.empty()){
                qsz = q.size();
                while(qsz){
                    qsz--;
                    tmp = q.front();
                    q.pop();
                    if(qsz) tmp->next = q.front();
                    if(tmp->left) q.push(tmp->left);
                    if(tmp->right) q.push(tmp->right);
                } 
            }
            return;
        }
    };
    

    Use one node pointer tmp and a queue.
    For each level, it point every node to the next neighborhood node. Then put all their child node into the queue.


Log in to reply
 

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