Java for LeetCode 230 Kth Smallest Element in a BST

时间:2023-03-08 17:08:33

解题思路:

直接修改中序遍历函数即可,JAVA实现如下:

int res = 0;
int k = 0; public int kthSmallest(TreeNode root, int k) {
this.k = k;
inorderTraversal(root);
return res;
} public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null)
return list;
if (root.left != null && list.size() < k)
list.addAll(inorderTraversal(root.left));
list.add(root.val);
if (root.right != null && list.size() < k)
list.addAll(inorderTraversal(root.right));
if(list.size()==k){
res=list.get(k-1);
return list;
}
return list;
}