leetcode 230. kth smallest element in a bst



  1. Kth Smallest Element in a BST:题目链接

递归

思路:利用二分搜索树的特性 对其中序遍历可以得到一个从小到大的顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  {

public int count = 0;
public int res = 0;

public int kthSmallest(TreeNode root, int k) {
if (root == null) {
return 0;
}
kthSmallest(root.left, k); // 递归访问左子树
count++; // 访问根
if (count == k) {
res = root.val;
return res;
}
kthSmallest(root.right, k); // 访问右子树
return res;
}
}