Where is the problem in my code?(C, Morris, iterative)


  • 0
    C
    int kthSmallest(struct TreeNode* root, int k) {
    int count = 0; // count the kth elem
    struct TreeNode *cur = root, *tmp = NULL;
    while(cur){
        if(!cur->left){
            if(++count == k) return cur->val;
            cur = cur->right;
        }
        else{
            tmp = cur->left;
            while(tmp->right && tmp->right != cur) tmp = tmp->right;
            if(tmp->right == NULL){ 
                tmp->right = cur; 
                cur = cur->left;
            }
            else{ 
                tmp->right = NULL; 
                if(++count == k) return cur->val;
                cur = cur->right;
            }
        }
    }
    

    }


Log in to reply
 

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