22ms c++ solution beats 98%


  • 0
    M

    Simple level order traversal.

    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(!root) return ;
            queue<TreeLinkNode*> q;
            q.push(root);
            int cur = 1, next = 0;
            while(!q.empty()){
                while(cur--) {
                    TreeLinkNode *p = q.front();
                    q.pop();
                    if(cur) p->next = q.front();
                    if(p->left) { q.push(p->left); next++; }
                    if(p->right) { q.push(p->right); next++; }
                }
                
                cur = next;
                next = 0;
            }
        }
    };
    

Log in to reply
 

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