[c++] use queue solution,o(n)time and constant memory


  • 0
    9
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(!root)   return ;
            queue<TreeLinkNode*> q;
            TreeLinkNode *s=root;
            TreeLinkNode *pre;
            q.push(s);
            while(!q.empty())
            {
                int count=q.size();
                for(int i=0;i<count-1;i++)
                {
                    if(q.front()->left) q.push(q.front()->left);
                    if(q.front()->right) q.push(q.front()->right);
                    pre=q.front();
                    q.pop();
                    pre->next=q.front();
                }
                if(q.front()->left) q.push(q.front()->left);
                if(q.front()->right) q.push(q.front()->right);
                q.pop();
            }
        }
    };

  • 0
    S

    I don't think it is constant space if you use a queue.
    The maximum size of the queue should be number of node in each level.


Log in to reply
 

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