Why my cpp solution is wrong


  • 0
    Y
    /**
     * Definition for binary tree with next pointer.
     * struct TreeLinkNode {
     *  int val;
     *  TreeLinkNode *left, *right, *next;
     *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(root==NULL)
                return ;
            if(root->left)
            {
                if(root->right)
                    root->left->next=root->right;
                else 
                {
                   TreeLinkNode * p=root;
                   while(p->next)    // If root has next ,check root->next whether its left or right exits? If left and right don't exit , find  root->next->next ... do the same thing until next==NULL
                   {
                        if(p->next->left)
                        {
                             root->left->next=p->next->left;
                             break;
                        }
                       else if(p->next->right)
                       {
                             root->left->next=p->next->right;
                             break;
                       }
                       p=p->next;
                   }
                }
            }
            if(root->right)
            {
                TreeLinkNode * p=root;
                while(p->next)
                {
                    if(p->next->left)
                     {
                         root->right->next=p->next->left;
                         break;
                     }
                     else if(p->next->right)
                     {
                         root->right->next=p->next->right;
                         break;
                     }
                     p=p->next;
                }
            }
            connect(root->left);
            connect(root->right);
        }
    };
    

    This problems is similar to Populating Next Right Pointers in Each Node 。
    So I use the same method and make some change ( use while-loop ) However , I cannot find where my mistake is ? Thanks


Log in to reply
 

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