Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * We can collect the values in ascending order by traveling the BST with inorder way. 
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        List<Integer> sort = new ArrayList<>();
        dfs(root, k, sort);
        return sort.get(k - 1);
    }
    
    private void dfs(TreeNode root, int k, List<Integer> sort) {
        if (root == null || sort.size() >= k) {
            return;
        }
        dfs(root.left, k, sort);
        sort.add(root.val);
        dfs(root.right, k, sort);
    }
}