Easy to understand, answer the follow up question

  • 1
    public int kthSmallest(TreeNode root, int k) {
       PriorityQueue<Integer> queue = new PriorityQueue<>(k, Collections.reverseOrder());
        kthHelper(queue, root, k);
        return queue.peek();
    private void kthHelper(PriorityQueue<Integer> queue, TreeNode root, int k) {
        if (root == null || queue.size() >= k) return;
       kthHelper(queue, root.left, k);
        if (queue.size() >= k) return;
        if (root.right != null) kthHelper(queue, root.right, k);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.