Runtime error for my Morris solution which runs properly on my machine


  • 0
    E

    My code is like below and I encountered runtime error: Last executed input: {1,2}.
    This code can run without problem on my machine, passing many test cases including this one. I really hope someone could help me find out the bug. Thanks!

    //Morris preorder traversal, O(n) time and O(1) space
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> results;
            TreeNode* cur = root;
            while(cur) {
                if (cur->left == NULL) {
                    results.push_back(cur->val);
                    cur = cur->right;
                } else {
                    TreeNode* node = cur->left;
                    while (node->right && node->right != cur)
                        node = node->right;
                    if (node->right == NULL) {
                        node->right = cur;
                        results.push_back(cur->val);
                        cur = cur->left;
                    } else if (node->right == cur) {
                        node->right == NULL;
                        cur = cur->right;
                    }
                }
            }
        
            return results;
        }

Log in to reply
 

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