Simple solution using arraylist in java


#1

/**

  • Definition for binary tree

  • class TreeNode {

  • int val;
    
  • TreeNode left;
    
  • TreeNode right;
    
  • TreeNode(int x) {
    
  •  val = x;
    
  •  left=null;
    
  •  right=null;
    
  • }
    
  • }
    */
    public class Solution {
    public void getl(TreeNode A,int B,ArrayList lst,int count){
    if(A==null){
    return ;
    }

     getl(A.left,B,lst,count);
     lst.add(A.val);
     count++;
     if(count==B){
         return;
     }
     getl(A.right,B,lst,count);
    

    }
    public int kthsmallest(TreeNode A, int B) {
    ArrayList lst = new ArrayList();
    int count =0;
    getl(A,B,lst,count);
    return lst.get(B-1);
    }
    }