Kth smallest element in tree


#1
public class Solution {
    int res;
    public int kthsmallest(TreeNode a, int b) {
        inOrderTraversal(a,b);
        return res;
    }
    private void inOrderTraversal(TreeNode a, int b) {
        if(a==null || b==0) return;
        inOrderTraversal(a.left, b);
        b--;
        if(b==0)    res=a.val;
        inOrderTraversal(a.right, b);
    }
}

#2

Don’t you have to pass ‘b’ by reference to inOrderTraversal ?


#3

Yes, bruh we need to pass you are a genius !!!


#4

Yes, you can add a new int as global variable and remove int b argument from the method (inOrderTraversal) but it will be like:

public class Solution {
int res,b;
public int kthsmallest(TreeNode a, int b) {
inOrderTraversal(a,b);
this.b=b;
return res;
}