# 1ms Java recursive solution

• ``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
List<Integer> list = new ArrayList();
fillList(root, list, k);
return list.get(k-1);
}
private void fillList(TreeNode root, List<Integer> list, int k) {
if(root == null) return;
else if(list.size() < k){
fillList(root.left, list, k);
list.add(root.val);
fillList(root.right, list, k);
}
return;
}
}
``````

• Below is 0ms, O(1) space solution (however it has global variables)

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int val = 0;
private int curr = 0;
public int kthSmallest(TreeNode root, int k) {
fillList(root, k);
return val;
}
private void fillList(TreeNode root, int k) {
if(root == null) return;
else if(curr < k){
fillList(root.left, k);
curr++;
if(curr == k) val = root.val;
fillList(root.right, k);
}
return;
}
}
``````

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