Thought my C code is accepted, the Run Code still confuses me.


  • 1
    W
    int kthSmallest(struct TreeNode* root, int k) {
        struct TreeNode* stack[1000];
        int count = 0, top = 0;
    
        while(count < k) {
            if (root != NULL) {
                stack[top++] = root;
                root = root->left;
            }
            else {
                root = stack[--top];
                count++;
                root = root->right;
            }
        }
    
        return stack[top]->val;
    }
    

    but when I use the Testcases as follows:

    [1,2,3,4]
    1/2/3/4    // four values of k
    

    the Output squence is 4/2/1/3. But it should be 1/2/3/4, isn't it? : (


  • 0

    You can't use 1/2/3/4 as four values of k.

    If you need to run your function with 4 values of k, you should enter this in custom input:

    [1,2,3,4]
    1
    [1,2,3,4]
    2
    [1,2,3,4]
    3
    [1,2,3,4]
    4

  • 0
    W

    What I mean is that when the input is:
    [1,2,3,4]
    1
    the expect output is:
    4
    But I thought the 1thSmallest value in the BST should be 1, or where did I go wrong?


  • 0

    The tree has to be a BST. [1,2,3,4] is not a BST.


  • 0
    W

    oh, I forgot that. Thanks for answering my foolish question.


Log in to reply
 

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