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.
代码如下:
/**
* 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<>();
list=midTree(root); return list.get(k-1);
}
public List<Integer> midTree(TreeNode root){
List<Integer> list=new ArrayList<>(); if(root.left!=null)
list.addAll(midTree(root.left)); list.add(root.val);
if(root.right!=null)
list.addAll(midTree(root.right)); return list;
}
}