230. Kth Smallest Element in a BST

class Solution {
    int count = 0;
    public int kthSmallest(TreeNode root, int k) {
        // in order trasversal
        if (root==null) return -1;
        int leftVal = kthSmallest(root.left, k);
        if (leftVal>=0) return leftVal;
        count++;
        if(count==k) return root.val;
        return kthSmallest(root.right, k);
    }
}

Last updated