|
| 1 | +package binary_search_tree; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Description: https://leetcode.com/problems/kth-smallest-element-in-a-bst |
| 7 | + * Difficulty: Medium |
| 8 | + */ |
| 9 | +public class KthSmallestElementInBST { |
| 10 | + |
| 11 | + /** |
| 12 | + * Time complexity: O(h + k) |
| 13 | + * Space complexity: O(h) |
| 14 | + */ |
| 15 | + public int kthSmallestViaIterativeInorderTraversal(TreeNode root, int k) { |
| 16 | + Deque<TreeNode> stack = new LinkedList<>(); |
| 17 | + |
| 18 | + while (root != null || !stack.isEmpty()) { |
| 19 | + if (root != null) { |
| 20 | + stack.push(root); |
| 21 | + root = root.left; |
| 22 | + } else { |
| 23 | + root = stack.pop(); |
| 24 | + if (--k == 0) return root.val; |
| 25 | + root = root.right; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return -1; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Time complexity: O(n) |
| 34 | + * Space complexity: O(n) |
| 35 | + */ |
| 36 | + public int kthSmallestViaRecursiveInorderTraversal(TreeNode root, int k) { |
| 37 | + List<Integer> inorder = new ArrayList<>(); |
| 38 | + traverseInorder(root, inorder); |
| 39 | + |
| 40 | + return inorder.get(k - 1); |
| 41 | + } |
| 42 | + |
| 43 | + private void traverseInorder(TreeNode root, List<Integer> result) { |
| 44 | + if (root == null) return; |
| 45 | + |
| 46 | + traverseInorder(root.left, result); |
| 47 | + result.add(root.val); |
| 48 | + traverseInorder(root.right, result); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Time complexity: O(nlog k) |
| 53 | + * Space complexity: O(h + k) |
| 54 | + */ |
| 55 | + public int kthSmallestViaMaxHeap(TreeNode root, int k) { |
| 56 | + Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b, a)); |
| 57 | + backtrack(root, maxHeap, k); |
| 58 | + |
| 59 | + return maxHeap.peek(); |
| 60 | + } |
| 61 | + |
| 62 | + private void backtrack(TreeNode root, Queue<Integer> maxHeap, int k) { |
| 63 | + if (root == null) return; |
| 64 | + |
| 65 | + maxHeap.offer(root.val); |
| 66 | + if (maxHeap.size() > k) maxHeap.poll(); |
| 67 | + |
| 68 | + backtrack(root.left, maxHeap, k); |
| 69 | + backtrack(root.right, maxHeap, k); |
| 70 | + } |
| 71 | + |
| 72 | + private static class TreeNode { |
| 73 | + int val; |
| 74 | + TreeNode left; |
| 75 | + TreeNode right; |
| 76 | + } |
| 77 | +} |
0 commit comments