Works on my CodeBlocks while Runtime Error on leetcode [C++]Last executed input: {2,3,3,4,5,4,5}


  • 0
    Y
    struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    

    };

        bool isSymmetric(TreeNode *root) {
        if(root==NULL) return true;
    
        TreeNode* pre1 = root->left;
        TreeNode* root1 = root->left;
        TreeNode* pre2 = root->right;
        TreeNode* root2 = root->right;
        if( root1==NULL || root2==NULL) return ( root1==NULL && root2==NULL );
    
        while(root1 && root2){
            if( ((root1->left)==NULL || (root2->right)==NULL) && (root1->left!=NULL || root2->right!=NULL) ) return false;
    
            if( (root1->left)==NULL && (root2->right)==NULL){
                if(root1->val != root2->val) return false;
                //
                pre1 = root1;
                root1 = root1->right;
                pre2 = root2;
                root2 = root2->left;
            }else{
                TreeNode *p1,*p2;
                for(p1=root1->left; p1->right && p1->right!=root1; p1=p1->right);
                for(p2=root2->right; p2->left && p2->left!=root2; p2=p2->left);
    
                if( ((p1->right)==NULL || (p2->left)==NULL) && ( (p1->right)!=NULL || (p2->left)!=NULL ) ) return false;
                if( (p1->right)==NULL && (p2->left)==NULL ){
                    p1->right = root1;
                    root1=root1->left;
                    p2->left = root2;
                    root2=root2->right;
                }else{
                    p1->right = NULL;
                    p2->left = NULL;
                    if(root1->val != root2->val) return false;
                    //
                    pre1 = root1;
                    root1 = root1->right;
                    pre2 = root2;
                    root2 = root2->left;
                }
            }
        }
    
        return root1==NULL && root2==NULL;
    }
    

    ===================================================
    {
    TreeNode node1(2);
    TreeNode node2(3);
    TreeNode node3(3);
    TreeNode node4(4);
    TreeNode node5(5);
    TreeNode node6(4);
    TreeNode node7(5);

    node1.left = &node2;
    node1.right = &node3;
    
    node2.left = &node4;
    node2.right = &node5;
    node3.left = &node6;
    node3.right = &node7;
    
    cout << isSymmetric(&node1) << endl;;
    return 0;
    

    }


Log in to reply
 

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