public class Solution {
public int kthSmallest(TreeNode root, int k) {
Map<TreeNode, Integer> counts = new HashMap<>();
calculateCounts(root, counts);
return quickSelectOnTree(root, k, counts);
}
private int calculateCounts(TreeNode root, Map<TreeNode, Integer> counts) {
if (root == null) {
counts.put(root, 0);
return 0;
}
int left = calculateCounts(root.left, counts);
int right = calculateCounts(root.right, counts);
counts.put(root, left + right + 1);
return left + right + 1;
}
private int quickSelectOnTree(TreeNode root, int k, Map<TreeNode, Integer> counts) {
if (root == null) {
return -1;
}
int left = counts.get(root.left);
if (left >= k) {
return quickSelectOnTree(root.left, k, counts);
}
if (left + 1 == k) {
return root.val;
}
return quickSelectOnTree(root.right, k - left - 1, counts);
}
}
Comments
Post a Comment