? ? ? ? 题目描述:给定一个二叉搜索树的根节点?root ?,和一个整数?k ?,请你设计一个算法查找其中第?k ?个最小元素(从 1 开始计数)。
? ? ? ? 编码实现:
public int kthSmallest(TreeNode root, int k) {
int leftCount = countNodes(root.left);
if (leftCount >= k) {
return kthSmallest(root.left, k);
} else if (leftCount + 1 == k) {
return root.val;
} else {
return kthSmallest(root.right, k - 1 - leftCount);
}
}
public int countNodes(TreeNode n) {
if (null == n){
return 0;
}
return 1 + countNodes(n.left) + countNodes(n.right);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
|