题目链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/submissions/
二分查找树(BST)的性质——任何一个节点的值均大于左子树的任意节点值,而小于右子树的任意节点值。
这样就可知道,最小值的一个节点在树的最左端,最大值的一个节点在树的最右端。
树从小到大顺序刚好满足树的中序遍历。因而,我们可以用中序遍历来处理。
java代码实现:
class Solution {
private int count, res;
public int kthSmallest(TreeNode root, int k) {
if (root.left != null) kthSmallest(root.left, k);
if (++count == k) res = root.val;
if (root.right != null) kthSmallest(root.right, k);
return res;
}
}