Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int kthSmallest(TreeNode root, int k) {
12         List<Integer> list=new ArrayList<>();
13         list=midTree(root);
14         
15         return list.get(k-1);
16     }
17     public List<Integer> midTree(TreeNode root){
18         List<Integer> list=new ArrayList<>();
19         
20          if(root.left!=null)
21              list.addAll(midTree(root.left));
22         
23          list.add(root.val);
24          if(root.right!=null)
25               list.addAll(midTree(root.right));
26          
27          return list;
28     }
29 }