vendredi 28 janvier 2022

Kth Smallest Element in a BST: Wrong output

Given a binary search tree, I am required to find the Kth smallest element in the bst.

I think I have understood the logic that I need to implement, but my code it is not giving the desired output.

Example: Input: root = [5,3,6,2,4,null,null,1], k = 3

      5
     / \
    3   6
   / \
  2   4
 /
1

The expected output is: 3

but my code outputs this:0

My C++ Code below:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {

public:

    int ans;
    int key;
    void inorder(TreeNode* root)
    {
        if(root==NULL)
            return;
        inorder(root->left);
        if(--key==0)
            ans=root->val;
        inorder(root->right);
    }
    int kthSmallest(TreeNode* root, int k) {
        if(root==NULL)
            return 0;
        int key=k;
        inorder(root);
        return ans;
    }
};

Where is the mistake?

Aucun commentaire:

Enregistrer un commentaire