|
| 1 | +<h1 align='center'>Two - Sum IV - Input is - BST</h1> |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +**Problem URL :** [Two Sum IV - Input is BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/) |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +## Problem Explanation |
| 11 | +**Problem:** |
| 12 | +The problem "Two Sum IV - Input is a BST" asks us to determine if there are two nodes in a given Binary Search Tree (BST) whose values add up to a specific target integer \( k \). |
| 13 | + |
| 14 | +**Example:** |
| 15 | +Let's say we have the following BST: |
| 16 | +``` |
| 17 | + 5 |
| 18 | + / \ |
| 19 | + 3 6 |
| 20 | + / \ \ |
| 21 | + 2 4 7 |
| 22 | +``` |
| 23 | +If \( k = 9 \), there are two nodes, 2 and 7, which sum to 9. Therefore, the function should return `true`. However, if \( k = 28 \), no such pair of nodes exists, so it should return `false`. |
| 24 | + |
| 25 | +**Understanding the Problem:** |
| 26 | +- We are given a BST and an integer \( k \). |
| 27 | +- Our task is to check if there are two values in the tree that add up to \( k \). |
| 28 | +- Since it's a BST, an in-order traversal will give us the values in sorted order, which we can then use with a two-pointer technique to find the pair. |
| 29 | + |
| 30 | +## Problem Solution |
| 31 | +```cpp |
| 32 | +/** |
| 33 | + * Definition for a binary tree node. |
| 34 | + * struct TreeNode { |
| 35 | + * int val; |
| 36 | + * TreeNode *left; |
| 37 | + * TreeNode *right; |
| 38 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 39 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 40 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 41 | + * }; |
| 42 | + */ |
| 43 | +class Solution { |
| 44 | +public: |
| 45 | + void inOrder(TreeNode* root, vector<int> &inOrderVal){ |
| 46 | + if(root == NULL) return; |
| 47 | + |
| 48 | + inOrder(root -> left, inOrderVal); |
| 49 | + inOrderVal.push_back(root -> val); |
| 50 | + inOrder(root -> right, inOrderVal); |
| 51 | + } |
| 52 | + bool findTarget(TreeNode* root, int k) { |
| 53 | + vector<int> inOrderVal; |
| 54 | + |
| 55 | + inOrder(root, inOrderVal); |
| 56 | + |
| 57 | + int i = 0; |
| 58 | + int j = inOrderVal.size() -1; |
| 59 | + |
| 60 | + while(i < j){ |
| 61 | + int sum = inOrderVal[i] + inOrderVal[j]; |
| 62 | + |
| 63 | + if(sum == k) return true; |
| 64 | + else if(sum > k) j--; |
| 65 | + else i++; |
| 66 | + } |
| 67 | + |
| 68 | + return false; |
| 69 | + } |
| 70 | +}; |
| 71 | +``` |
| 72 | +
|
| 73 | +## Problem Solution Explanation |
| 74 | +
|
| 75 | +Let's go through the code step-by-step. |
| 76 | +
|
| 77 | +```cpp |
| 78 | +class Solution { |
| 79 | +public: |
| 80 | +``` |
| 81 | +- This defines a `Solution` class with public member functions. |
| 82 | +- The public keyword means all functions and variables following it are accessible from outside the class. |
| 83 | + |
| 84 | +### In-Order Traversal Helper Function |
| 85 | + |
| 86 | +```cpp |
| 87 | + void inOrder(TreeNode* root, vector<int> &inOrderVal) { |
| 88 | +``` |
| 89 | +- `inOrder` is a helper function that takes two arguments: |
| 90 | + - A pointer `root` to the current node in the BST. |
| 91 | + - A reference to `vector<int> inOrderVal`, which will store the values of the nodes in sorted order. |
| 92 | + |
| 93 | +- This function will be used to traverse the BST in in-order (left, root, right), resulting in a sorted list of node values in the `inOrderVal` vector. |
| 94 | +
|
| 95 | +```cpp |
| 96 | + if(root == NULL) return; |
| 97 | +``` |
| 98 | +- **Explanation:** If the `root` is `NULL`, it means we’ve reached a leaf node or the tree is empty, so we simply return without doing anything. |
| 99 | + |
| 100 | +- **Example:** For a BST like this: |
| 101 | + ``` |
| 102 | + 5 |
| 103 | + / \ |
| 104 | + 3 6 |
| 105 | + ``` |
| 106 | + When `inOrder` is called with `root = NULL`, it will just return. |
| 107 | + |
| 108 | +```cpp |
| 109 | + inOrder(root -> left, inOrderVal); |
| 110 | +``` |
| 111 | +- **Explanation:** This line makes a recursive call to traverse the left subtree of the current node. |
| 112 | +- **Example:** In the example BST: |
| 113 | + ``` |
| 114 | + 5 |
| 115 | + / \ |
| 116 | + 3 6 |
| 117 | + ``` |
| 118 | + When `inOrder` is first called with `root` pointing to 5, it will call itself with `root->left` (node 3). |
| 119 | +
|
| 120 | +```cpp |
| 121 | + inOrderVal.push_back(root -> val); |
| 122 | +``` |
| 123 | +- **Explanation:** This line adds the value of the current node to the `inOrderVal` vector. Since we’re doing an in-order traversal, this line will be reached after the left subtree has been traversed. |
| 124 | +- **Example:** In our example: |
| 125 | + - When the traversal reaches node 3, `inOrderVal.push_back(3)` adds 3 to the vector. |
| 126 | + - Similarly, when node 5 is reached, 5 is added, and so on. |
| 127 | + |
| 128 | +```cpp |
| 129 | + inOrder(root -> right, inOrderVal); |
| 130 | +``` |
| 131 | +- **Explanation:** This line makes a recursive call to traverse the right subtree of the current node. |
| 132 | +- **Example:** Continuing with the example: |
| 133 | + - After node 5 is added, the function will recursively traverse the right subtree (node 6). |
| 134 | + |
| 135 | +- **Final Result of Traversal:** For a BST with nodes 5, 3, and 6, the vector `inOrderVal` will end up as `[3, 5, 6]`. |
| 136 | +
|
| 137 | +### Main Function to Find the Target Sum |
| 138 | +
|
| 139 | +```cpp |
| 140 | + bool findTarget(TreeNode* root, int k) { |
| 141 | +``` |
| 142 | +- **Explanation:** This is the main function that will return `true` if there are two distinct values in the BST that add up to `k`, and `false` otherwise. |
| 143 | +- **Parameters:** |
| 144 | + - `TreeNode* root` is the root node of the BST. |
| 145 | + - `int k` is the target sum we’re looking for. |
| 146 | + |
| 147 | +```cpp |
| 148 | + vector<int> inOrderVal; |
| 149 | +``` |
| 150 | +- **Explanation:** This initializes an empty vector `inOrderVal` to store the sorted values of the BST nodes after in-order traversal. |
| 151 | + |
| 152 | +```cpp |
| 153 | + inOrder(root, inOrderVal); |
| 154 | +``` |
| 155 | +- **Explanation:** Calls the `inOrder` function to fill the `inOrderVal` vector with the sorted values of the nodes. |
| 156 | +
|
| 157 | +```cpp |
| 158 | + int i = 0; |
| 159 | + int j = inOrderVal.size() - 1; |
| 160 | +``` |
| 161 | +- **Explanation:** Initializes two pointers: |
| 162 | + - `i` starts at the beginning of `inOrderVal` (smallest value). |
| 163 | + - `j` starts at the end of `inOrderVal` (largest value). |
| 164 | + |
| 165 | +- **Example:** If `inOrderVal` is `[2, 3, 4, 5, 6, 7]`, `i` points to 2, and `j` points to 7 initially. |
| 166 | + |
| 167 | +### Two-Pointer Technique for Finding Sum |
| 168 | + |
| 169 | +```cpp |
| 170 | + while(i < j) { |
| 171 | +``` |
| 172 | +- **Explanation:** Starts a `while` loop that will continue as long as `i` is less than `j`. This loop checks pairs of values to see if their sum matches \( k \). |
| 173 | +
|
| 174 | +```cpp |
| 175 | + int sum = inOrderVal[i] + inOrderVal[j]; |
| 176 | +``` |
| 177 | +- **Explanation:** Calculates the sum of the values at indices `i` and `j`. |
| 178 | + |
| 179 | +- **Example:** If `inOrderVal` is `[2, 3, 4, 5, 6, 7]` and `k = 9`: |
| 180 | + - Initially, `sum = 2 + 7 = 9`. |
| 181 | + |
| 182 | +```cpp |
| 183 | + if(sum == k) return true; |
| 184 | +``` |
| 185 | +- **Explanation:** If the sum is equal to \( k \), it means we’ve found two numbers in the BST that add up to \( k \), so the function returns `true`. |
| 186 | + |
| 187 | +- **Example:** If `sum = 9` (our target), the function will return `true`. |
| 188 | + |
| 189 | +```cpp |
| 190 | + else if(sum > k) j--; |
| 191 | +``` |
| 192 | +- **Explanation:** If the sum is greater than \( k \), we decrease the `j` pointer by 1 to check the next smaller value. This is because the values in `inOrderVal` are sorted, so moving `j` to the left decreases the sum. |
| 193 | + |
| 194 | +- **Example:** If `sum = 10` and `k = 9`, `j` moves from 5 to 4. |
| 195 | + |
| 196 | +```cpp |
| 197 | + else i++; |
| 198 | +``` |
| 199 | +- **Explanation:** If the sum is less than \( k \), we increase the `i` pointer by 1 to check the next larger value. This increases the sum since we are moving towards larger values in the sorted list. |
| 200 | + |
| 201 | +- **Example:** If `sum = 8` and `k = 9`, `i` moves from 0 to 1. |
| 202 | + |
| 203 | +```cpp |
| 204 | + } |
| 205 | +``` |
| 206 | +- **Explanation:** This closes the `while` loop. If we exit the loop, it means no pair of values in the BST adds up to \( k \). |
| 207 | + |
| 208 | +```cpp |
| 209 | + return false; |
| 210 | + } |
| 211 | +}; |
| 212 | +``` |
| 213 | +- **Explanation:** If no matching sum was found, the function returns `false`. |
| 214 | + |
| 215 | + |
| 216 | +### Example Walkthrough |
| 217 | + |
| 218 | +**Example:** |
| 219 | +BST: |
| 220 | +``` |
| 221 | + 5 |
| 222 | + / \ |
| 223 | + 3 6 |
| 224 | + / \ \ |
| 225 | + 2 4 7 |
| 226 | +``` |
| 227 | +- **Target Sum:** \( k = 9 \) |
| 228 | + |
| 229 | +- **In-Order Traversal:** |
| 230 | + - `inOrderVal = [2, 3, 4, 5, 6, 7]` |
| 231 | + |
| 232 | +- **Two-Pointer Technique:** |
| 233 | + - Initialize `i = 0`, `j = 5`. |
| 234 | + - Calculate `sum = inOrderVal[i] + inOrderVal[j] = 2 + 7 = 9`. |
| 235 | + - Since `sum == k`, the function returns `true`. |
| 236 | + |
| 237 | + |
| 238 | +### Step 4: Time and Space Complexity |
| 239 | + |
| 240 | +1. **Time Complexity:** |
| 241 | + - The in-order traversal of a BST takes **O(n)** time, where \( n \) is the number of nodes. |
| 242 | + - The two-pointer search also takes **O(n)** time. |
| 243 | + - Thus, the overall time complexity is **O(n)**. |
| 244 | + |
| 245 | +2. **Space Complexity:** |
| 246 | + - The vector `inOrderVal` takes **O(n)** space to store the in-order values of all nodes. |
| 247 | + - The recursive stack for `inOrder` traversal could also take **O(h)** space, where \( h \) is the height of the tree. |
| 248 | + - Therefore, the total space complexity is **O(n)**. |
| 249 | + |
| 250 | +### Step 5: Additional Recommendations |
| 251 | + |
| 252 | +- **Edge Cases to Consider:** |
| 253 | + - If the BST has only one node, there’s no pair to check, so return `false`. |
| 254 | + - If \( k \) is smaller than the smallest value or larger than the sum of the two largest values in the tree, return `false` early. |
| 255 | + |
| 256 | +- **Alternative Approach:** |
| 257 | + - If memory usage is a concern, consider an in-place solution using a stack for in-order traversal without storing values in an extra vector. |
| 258 | + |
| 259 | +This approach should give students a strong foundation for solving similar problems with sorted arrays and BSTs efficiently. |
0 commit comments