|
| 1 | +<h1 align='center'>Kth - Smallest - Element - In a - BST</h1> |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +**Problem URL :** [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +## Problem Explanation |
| 11 | +Given a Binary Search Tree (BST) and an integer `k`, the task is to find the `k`th smallest element in the BST. In a BST, the in-order traversal (left-root-right) produces elements in ascending order. |
| 12 | + |
| 13 | +**Example**: |
| 14 | +Let's look at a couple of examples: |
| 15 | + |
| 16 | +1. **Example 1**: |
| 17 | + ```plaintext |
| 18 | + 3 |
| 19 | + / \ |
| 20 | + 1 4 |
| 21 | + \ |
| 22 | + 2 |
| 23 | + ``` |
| 24 | + - If `k = 1`, the output should be `1` (the smallest element). |
| 25 | + - If `k = 3`, the output should be `3` (the third smallest element). |
| 26 | + |
| 27 | +- If `k = 3`, the output should be `3`. |
| 28 | + |
| 29 | +**Constraints**: |
| 30 | +1. The number of nodes in the tree ranges from `1` to `10^4`. |
| 31 | +2. `k` is always valid, meaning `1 <= k <= total number of nodes`. |
| 32 | + |
| 33 | +**Edge Cases**: |
| 34 | +1. If there’s only one node, `k` must be `1`, so we return that node’s value. |
| 35 | +2. A very small or very large `k` should be checked correctly based on node count. |
| 36 | + |
| 37 | +### Step 2: Approach |
| 38 | + |
| 39 | +Since an in-order traversal of a BST produces sorted elements, the `k`th smallest element is simply the `k`th node visited in in-order. |
| 40 | + |
| 41 | +**Steps**: |
| 42 | +1. Perform an in-order traversal, which will naturally visit nodes in ascending order. |
| 43 | +2. Use a counter (`i`) to keep track of the number of nodes visited. |
| 44 | +3. Once `i` reaches `k`, we’ve found the `k`th smallest element and can return it immediately without further traversals. |
| 45 | + |
| 46 | +## Problem Solution |
| 47 | +```cpp |
| 48 | +/** |
| 49 | + * Definition for a binary tree node. |
| 50 | + * struct TreeNode { |
| 51 | + * int val; |
| 52 | + * TreeNode *left; |
| 53 | + * TreeNode *right; |
| 54 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 55 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 56 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 57 | + * }; |
| 58 | + */ |
| 59 | +class Solution { |
| 60 | +public: |
| 61 | + int solve(TreeNode* root, int &i, int k){ |
| 62 | + if(root == NULL) return -1; |
| 63 | + |
| 64 | + int left = solve(root -> left, i, k); |
| 65 | + if(left != -1) return left; |
| 66 | + |
| 67 | + i++; |
| 68 | + if(i == k) return root -> val; |
| 69 | + |
| 70 | + return solve(root -> right, i, k); |
| 71 | + } |
| 72 | + int kthSmallest(TreeNode* root, int k) { |
| 73 | + |
| 74 | + int i = 0; |
| 75 | + int ans = solve(root, i, k); |
| 76 | + |
| 77 | + return ans; |
| 78 | + } |
| 79 | +}; |
| 80 | +``` |
| 81 | +
|
| 82 | +## Problem Solution Explanation |
| 83 | +Here’s a detailed explanation for solving the "Kth Smallest Element in a BST" problem from LeetCode using the provided code and structure: |
| 84 | +
|
| 85 | +```cpp |
| 86 | +class Solution { |
| 87 | +public: |
| 88 | + int solve(TreeNode* root, int &i, int k){ |
| 89 | + if(root == NULL) return -1; |
| 90 | +``` |
| 91 | +- **Function**: `solve` |
| 92 | +- **Purpose**: Recursively finds the `k`th smallest element. |
| 93 | +- **Parameters**: |
| 94 | + - `TreeNode* root`: Pointer to the current node. |
| 95 | + - `int &i`: Reference counter for the number of nodes visited so far. |
| 96 | + - `int k`: The target position (kth smallest element). |
| 97 | + |
| 98 | +- **Base Case**: If `root` is `NULL`, we return `-1`, as there’s nothing to process. |
| 99 | + |
| 100 | +```cpp |
| 101 | + int left = solve(root->left, i, k); |
| 102 | + if(left != -1) return left; |
| 103 | +``` |
| 104 | +- **Left Subtree Traversal**: Recursively call `solve` on the left subtree. |
| 105 | +- **Check Return**: If the left subtree call found the `k`th smallest element (returning a non-`-1` value), immediately return it, as it will propagate up the recursive calls. |
| 106 | + |
| 107 | +```cpp |
| 108 | + i++; |
| 109 | + if(i == k) return root->val; |
| 110 | +``` |
| 111 | +- **Increment Counter**: After visiting the left subtree, we increase the counter `i` to reflect the current node visit. |
| 112 | +- **Check Position**: If `i` equals `k`, we’ve found the `k`th smallest element and return the current node’s value (`root->val`). |
| 113 | + |
| 114 | +```cpp |
| 115 | + return solve(root->right, i, k); |
| 116 | + } |
| 117 | +``` |
| 118 | +- **Right Subtree Traversal**: If the `k`th smallest element hasn’t been found, we continue with the right subtree. |
| 119 | + |
| 120 | +```cpp |
| 121 | + int kthSmallest(TreeNode* root, int k) { |
| 122 | + int i = 0; |
| 123 | + int ans = solve(root, i, k); |
| 124 | + return ans; |
| 125 | + } |
| 126 | +}; |
| 127 | +``` |
| 128 | +- **Wrapper Function**: `kthSmallest` |
| 129 | + - Initializes the counter `i` to `0` and starts the recursion with `solve`. |
| 130 | + - Returns the result of `solve`, which is the `k`th smallest element. |
| 131 | +
|
| 132 | +### Step 4: Output Examples |
| 133 | +
|
| 134 | +1. **Example 1**: |
| 135 | + ```plaintext |
| 136 | + 3 |
| 137 | + / \ |
| 138 | + 1 4 |
| 139 | + \ |
| 140 | + 2 |
| 141 | + ``` |
| 142 | + **Input**: `k = 1` |
| 143 | + **Output**: `1` |
| 144 | + **Explanation**: The smallest element is `1`. |
| 145 | + |
| 146 | +3. **Edge Case (Single Node)**: |
| 147 | + ```plaintext |
| 148 | + 1 |
| 149 | + ``` |
| 150 | + **Input**: `k = 1` |
| 151 | + **Output**: `1` |
| 152 | + **Explanation**: A single-node tree has only one element, which is also the smallest. |
| 153 | + |
| 154 | +### Step 5: Time and Space Complexity |
| 155 | + |
| 156 | +**Time Complexity**: \(O(H + k)\) |
| 157 | +- **Traversal Cost**: In the best case, we may need to traverse only part of the tree to find the `k`th smallest element. The complexity is influenced by the height of the tree (`H`) and `k`. |
| 158 | + - In a balanced BST, `H = O(\log n)`, so the complexity becomes \(O(\log n + k)\). |
| 159 | + - In a worst-case scenario (skewed tree), `H` can be \(O(n)\), so the complexity could be \(O(n)\). |
| 160 | + |
| 161 | +**Space Complexity**: \(O(H)\) |
| 162 | +- **Recursive Stack**: The space complexity depends on the maximum depth of the recursive stack, which is the height `H` of the tree. |
| 163 | + - For a balanced tree, this would be \(O(\log n)\). |
| 164 | + - For a skewed tree, this could be \(O(n)\). |
| 165 | + |
| 166 | + |
| 167 | +### Additional Tips |
| 168 | + |
| 169 | +- **Edge Cases**: Always handle trees with a single node or cases where `k` is the number of nodes in the tree. |
| 170 | +- **Optimizations**: For extremely large trees, consider an iterative approach to minimize recursive overhead. |
| 171 | +- **Real-world Analogy**: Think of an in-order traversal as a sorted array, where each element corresponds to a position in the array. Finding the `k`th smallest element is like accessing the `k`th position in a sorted list. |
| 172 | + |
| 173 | +This method provides a clear, efficient way to find the `k`th smallest element in a BST by leveraging in-order traversal. |
0 commit comments