What is wrong in my code?


  • 0
    T
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
     int z=0,ans=0;
    int kthSmallest(struct TreeNode* root, int k) {
        
         
          t(root,k);
           return  ans;
    }
    void t(struct TreeNode* r,int k)
    {  // printf("C%d",z);
        if(r==NULL || z>k)
        {//printf("NULL");
            return;}
       t(r->left,k);
       z++;printf("%d",r->val);
       if(z==k)
        {  ans=r->val;}
       t(r->right,k); 
    }

  • 0
    J

    Global variables?

    int kthSmallest(struct TreeNode* root, int k) {
        int z=0,ans=0;
        t(root, k, &z, &ans);
        return  ans;
    }
    void t(struct TreeNode* r,int k, int * z, int * ans)
    {
        if(r==NULL) return;
        t(r->left,k, z, ans);
        (*z)++;
        if((*z) == k)
        {
            *ans = r->val;
            return;
        }
        t(r->right,k, z, ans); 
    }

  • 0
    L

    As joel6 has mentioned, it's the global variables' problem, you need to reset z and ans back to initial value in each call of the main function. It is extremely dangerous to use global variable while you do not realize that its value could be changed after calling the function.


Log in to reply
 

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