C Solution Using iterative method, but fail on Use Case for Tree with One Node only leetcode.


  • 0
    N

    Here is the C solution using iterative method. In leetcode it fail to pass the use case with single node in the tree.
    it works well with my local system with same use case. let me know if you find any flaw in the code. Thanks

    
    struct QList {
         struct TreeNode *node;
         struct QList *next;
    
    };
    
    struct QList *QTree = NULL;
    
    void AddQueue(struct TreeNode *node) {
    
            struct QList *temp = QTree, *NewNode;
    
    
            while (temp) {
                    if(!temp->next) break;
                    temp = temp->next;
            }
            NewNode = (struct QList *)malloc(sizeof(struct QList));
            if(!NewNode) {
                    printf("fail to create the new node for QList\n");
                    return;
            }
    
            NewNode->node = node;
            NewNode->next = NULL;
    
            if(!QTree) QTree = NewNode;
            else temp->next = NewNode;
    
            return;
    }
    struct TreeNode *PollQueue(void) {
    
            struct TreeNode *node = NULL;
            struct QList *temp = QTree;
    
    //      if(!temp) {
    //              printf("QList is empty\n");
    //              return NULL;
    //      }
    
            node = temp->node;
            QTree = temp->next;
    
            free(temp);
    
            return node;
    }
    
    bool isQueueEmpty(void)
    {
            if(!QTree) return true;
            return false;
    }
    
    
    bool isSymmetric(struct TreeNode* root) {
    
            struct TreeNode *t1, *t2;
    
            if (!root) return true;
            AddQueue(root);
            AddQueue(root);
            while ( !isQueueEmpty() ) {
                    t1 = PollQueue();
                    t2 = PollQueue();
                    if ((t1 == NULL) && (t2 == NULL)) continue;
                    if ((t1 == NULL) || (t2 == NULL)) return false;
                    if (t1->val != t2->val) return false;
                    AddQueue(t1->left);
                    AddQueue(t2->right);
                    AddQueue(t1->right);
                    AddQueue(t2->left);
            }
            return true;
    }
    
    

Log in to reply
 

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