Whats wrong with this C++ code -- Please Help


  • 0
    A

    Its failing for test case 34 . I am confused why its giving me 0 # 7 # as output:

    Input:	{2,1,3,0,7,9,1,2,#,1,0,#,#,8,8,#,#,#,#,7}
    Output:	{2,#,1,3,#,0,7,9,1,#,2,1,0,#,7,#}
    Expected:	{2,#,1,3,#,0,7,9,1,#,2,1,0,8,8,#,7,#}
    
    class Solution {
        public:
            void ConnectNode(TreeLinkNode *root, TreeLinkNode *node) {
                TreeLinkNode* temp = root->next;
                while(temp != NULL) {
                    if(temp->left != NULL) {
                        node->next = temp->left;
                        return;
                    } else {
                        if(temp->right != NULL) {
                            node->next = temp->right;
                            return;
                        } 
                    }
                    
                    temp = temp->next;
                }
                
            }
        
            void connect(TreeLinkNode *root) {
                if(root == NULL) {
                    return;
                }
                
                if(root->left) {
                    if(root->right) {
                        root->left->next = root->right;
                    } else {
                        ConnectNode(root, root->left);
                    }
                }
                
                if(root->right) {
                    if(root->next == NULL) {
                        root->right->next == NULL;
                    } else {
                        ConnectNode(root, root->right);
                    }
                }
                
                connect(root->left);
                connect(root->right);
            }
        };

  • 0
    S

    i am also facing the same problem .
    https://leetcode.com/discuss/38252/34-61-test-cases-passed
    Let me know if you found out...
    i am also tracking it..


  • 1
    S

    Got the bug:

    first right subtree should be travese else it might be a case when
    right subtree next pointer is not proccesed

    instead of

    connect(root->left);
      connect(root->right);
    

    use

       connect(root->right);   
        connect(root->left);

  • 0
    A

    Nice catch. Thank you!!


Log in to reply
 

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