|
| 1 | +<h1 align='center'>Convert - BST - To - Min Heap</h1> |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +**Problem URL :** [Convert BST to Min Heap](https://www.geeksforgeeks.org/convert-bst-min-heap/) |
| 6 | + |
| 7 | +**Problem Statement**: |
| 8 | +You are given a **Binary Search Tree (BST)**, and you need to convert it into a **Min Heap**. |
| 9 | + |
| 10 | +- **Binary Search Tree (BST)**: |
| 11 | + - A BST is a binary tree where for each node: |
| 12 | + - All values in the left subtree are smaller than the node's value. |
| 13 | + - All values in the right subtree are greater than the node's value. |
| 14 | + |
| 15 | +- **Min Heap**: |
| 16 | + - A Min Heap is a binary tree that satisfies the **heap property**: |
| 17 | + - The value of each node is **smaller** than the values of its children. |
| 18 | + - It’s a complete binary tree (i.e., all levels are filled except possibly the last level, which is filled from left to right). |
| 19 | + |
| 20 | +**Objective**: |
| 21 | +Convert the given **BST** into a **Min Heap**, but you must maintain the **heap property**. |
| 22 | + |
| 23 | +**Approach**: |
| 24 | +To solve this, you can use the following steps: |
| 25 | +1. **Extract All Elements from the BST in Sorted Order**: |
| 26 | + - Perform an **inorder traversal** on the BST. This traversal gives you the elements in **ascending order**. |
| 27 | + |
| 28 | +2. **Transform the BST into a Min Heap**: |
| 29 | + - After collecting the elements, you will use **preorder traversal** to assign values to the nodes. The **preorder traversal** ensures that you fill the tree in a top-to-bottom, left-to-right manner, which is necessary for a **Min Heap**. |
| 30 | + - The smallest elements from the sorted list will be assigned to the nodes, respecting the heap property. |
| 31 | + |
| 32 | +**Example**: |
| 33 | +- **Input BST**: |
| 34 | + ``` |
| 35 | + 4 |
| 36 | + / \ |
| 37 | + 2 6 |
| 38 | + / \ / \ |
| 39 | + 1 3 5 7 |
| 40 | + ``` |
| 41 | + |
| 42 | +- **Inorder Traversal of BST**: `[1, 2, 3, 4, 5, 6, 7]` |
| 43 | + |
| 44 | +- **Resulting Min Heap** (after transforming the BST into a Min Heap): |
| 45 | + ``` |
| 46 | + 1 |
| 47 | + / \ |
| 48 | + 2 3 |
| 49 | + / \ / \ |
| 50 | + 4 5 6 7 |
| 51 | + ``` |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +## Problem Solution |
| 57 | +```cpp |
| 58 | +#include <iostream> |
| 59 | +#include <vector> |
| 60 | +using namespace std; |
| 61 | + |
| 62 | +// Definition for a Node in the Binary Tree |
| 63 | +class Node { |
| 64 | +public: |
| 65 | + int data; |
| 66 | + Node* left; |
| 67 | + Node* right; |
| 68 | + |
| 69 | + // Constructor to create a new node with given value |
| 70 | + Node(int val) { |
| 71 | + this->data = val; |
| 72 | + this->left = NULL; |
| 73 | + this->right = NULL; |
| 74 | + } |
| 75 | +}; |
| 76 | + |
| 77 | +// Function to perform inorder traversal on the BST |
| 78 | +// This collects all node values in sorted order |
| 79 | +void inOrder(Node* root, vector<int>& nodes) { |
| 80 | + if (root == NULL) return; // Base case for recursion |
| 81 | + |
| 82 | + inOrder(root->left, nodes); // Traverse left subtree |
| 83 | + nodes.push_back(root->data); // Visit node and add its value to the vector |
| 84 | + inOrder(root->right, nodes); // Traverse right subtree |
| 85 | +} |
| 86 | + |
| 87 | +// Function to transform the BST to a Min Heap using preorder traversal |
| 88 | +// It assigns values from the sorted list to each node |
| 89 | +void inOrderToMinHeap(Node* root, vector<int>& nodes, int& index) { |
| 90 | + if (root == NULL) return; // Base case for recursion |
| 91 | + |
| 92 | + // Assign the current node with the next value in sorted order |
| 93 | + root->data = nodes[index++]; |
| 94 | + |
| 95 | + // Continue assigning values to left and right children |
| 96 | + inOrderToMinHeap(root->left, nodes, index); |
| 97 | + inOrderToMinHeap(root->right, nodes, index); |
| 98 | +} |
| 99 | + |
| 100 | +// Main function to convert BST to Min Heap |
| 101 | +void BST_to_MinHeap(Node* root) { |
| 102 | + if (root == NULL) { // Check for an empty tree |
| 103 | + cout << "Empty Tree" << endl; |
| 104 | + return; |
| 105 | + } |
| 106 | + |
| 107 | + vector<int> nodes; // Vector to store nodes in sorted order |
| 108 | + |
| 109 | + // Step 1: Store elements of BST in sorted order |
| 110 | + inOrder(root, nodes); |
| 111 | + |
| 112 | + int index = 0; |
| 113 | + // Step 2: Assign values from sorted list to nodes in preorder traversal |
| 114 | + inOrderToMinHeap(root, nodes, index); |
| 115 | +} |
| 116 | + |
| 117 | +// Function to print the tree in preorder to check Min Heap property |
| 118 | +void print(Node* root) { |
| 119 | + if (root == NULL) return; // Base case for recursion |
| 120 | + |
| 121 | + cout << root->data << " "; // Print current node |
| 122 | + print(root->left); // Print left subtree |
| 123 | + print(root->right); // Print right subtree |
| 124 | +} |
| 125 | + |
| 126 | +int main() { |
| 127 | + // Constructing a simple BST |
| 128 | + Node* root = new Node(4); |
| 129 | + root->left = new Node(2); |
| 130 | + root->right = new Node(6); |
| 131 | + root->left->left = new Node(1); |
| 132 | + root->left->right = new Node(3); |
| 133 | + root->right->left = new Node(5); |
| 134 | + root->right->right = new Node(7); |
| 135 | + |
| 136 | + // Convert BST to Min Heap |
| 137 | + BST_to_MinHeap(root); |
| 138 | + |
| 139 | + // Print the tree in preorder to verify Min Heap property |
| 140 | + cout << "Preorder of Min Heap : "; |
| 141 | + print(root); |
| 142 | + cout << endl; |
| 143 | + |
| 144 | + return 0; |
| 145 | +} |
| 146 | + |
| 147 | +``` |
| 148 | +
|
| 149 | +## Problem Solution Explanation |
| 150 | +```cpp |
| 151 | +#include <iostream> |
| 152 | +#include <vector> |
| 153 | +using namespace std; |
| 154 | +
|
| 155 | +// Definition for a Node in the Binary Tree |
| 156 | +class Node { |
| 157 | +public: |
| 158 | + int data; |
| 159 | + Node* left; |
| 160 | + Node* right; |
| 161 | + |
| 162 | + // Constructor to create a new node with given value |
| 163 | + Node(int val) { |
| 164 | + this->data = val; |
| 165 | + this->left = NULL; |
| 166 | + this->right = NULL; |
| 167 | + } |
| 168 | +}; |
| 169 | +``` |
| 170 | +- **Node Class**: |
| 171 | + - The `Node` class is defined for the binary tree nodes. Each node contains: |
| 172 | + - `data`: The value of the node. |
| 173 | + - `left`: Pointer to the left child node. |
| 174 | + - `right`: Pointer to the right child node. |
| 175 | + - The constructor initializes these values for each node. |
| 176 | + |
| 177 | +```cpp |
| 178 | +// Function to perform inorder traversal on the BST |
| 179 | +// This collects all node values in sorted order |
| 180 | +void inOrder(Node* root, vector<int>& nodes) { |
| 181 | + if (root == NULL) return; // Base case for recursion |
| 182 | + |
| 183 | + inOrder(root->left, nodes); // Traverse left subtree |
| 184 | + nodes.push_back(root->data); // Visit node and add its value to the vector |
| 185 | + inOrder(root->right, nodes); // Traverse right subtree |
| 186 | +} |
| 187 | +``` |
| 188 | +- **`inOrder` function**: |
| 189 | + - This is a standard recursive **inorder traversal** of a binary tree. |
| 190 | + - It collects the values of the nodes in **sorted order** in the `nodes` vector. |
| 191 | +
|
| 192 | +```cpp |
| 193 | +// Function to transform the BST to a Min Heap using preorder traversal |
| 194 | +// It assigns values from the sorted list to each node |
| 195 | +void inOrderToMinHeap(Node* root, vector<int>& nodes, int& index) { |
| 196 | + if (root == NULL) return; // Base case for recursion |
| 197 | +
|
| 198 | + // Assign the current node with the next value in sorted order |
| 199 | + root->data = nodes[index++]; |
| 200 | +
|
| 201 | + // Continue assigning values to left and right children |
| 202 | + inOrderToMinHeap(root->left, nodes, index); |
| 203 | + inOrderToMinHeap(root->right, nodes, index); |
| 204 | +} |
| 205 | +``` |
| 206 | +- **`inOrderToMinHeap` function**: |
| 207 | + - This function is used to convert the BST to a Min Heap. |
| 208 | + - It uses **preorder traversal** and assigns values to the nodes starting from the root. The sorted list of node values is used to assign values to the nodes. |
| 209 | + - The variable `index` tracks the current position in the sorted list of values. |
| 210 | + |
| 211 | +```cpp |
| 212 | +// Main function to convert BST to Min Heap |
| 213 | +void BST_to_MinHeap(Node* root) { |
| 214 | + if (root == NULL) { // Check for an empty tree |
| 215 | + cout << "Empty Tree" << endl; |
| 216 | + return; |
| 217 | + } |
| 218 | + |
| 219 | + vector<int> nodes; // Vector to store nodes in sorted order |
| 220 | + |
| 221 | + // Step 1: Store elements of BST in sorted order |
| 222 | + inOrder(root, nodes); |
| 223 | + |
| 224 | + int index = 0; |
| 225 | + // Step 2: Assign values from sorted list to nodes in preorder traversal |
| 226 | + inOrderToMinHeap(root, nodes, index); |
| 227 | +} |
| 228 | +``` |
| 229 | +- **`BST_to_MinHeap` function**: |
| 230 | + - This is the main function where the process begins. |
| 231 | + - First, it checks if the tree is empty and prints a message if true. |
| 232 | + - It calls the `inOrder` function to collect the nodes in sorted order. |
| 233 | + - Then, it calls `inOrderToMinHeap` to convert the tree into a Min Heap using the sorted values. |
| 234 | +
|
| 235 | +```cpp |
| 236 | +// Function to print the tree in preorder to check Min Heap property |
| 237 | +void print(Node* root) { |
| 238 | + if (root == NULL) return; // Base case for recursion |
| 239 | +
|
| 240 | + cout << root->data << " "; // Print current node |
| 241 | + print(root->left); // Print left subtree |
| 242 | + print(root->right); // Print right subtree |
| 243 | +} |
| 244 | +``` |
| 245 | +- **`print` function**: |
| 246 | + - This is a **preorder traversal** function used to print the tree after transformation. This helps verify the Min Heap property. |
| 247 | + - It prints the current node, then recursively prints the left and right children. |
| 248 | + |
| 249 | +```cpp |
| 250 | +int main() { |
| 251 | + // Constructing a simple BST |
| 252 | + Node* root = new Node(4); |
| 253 | + root->left = new Node(2); |
| 254 | + root->right = new Node(6); |
| 255 | + root->left->left = new Node(1); |
| 256 | + root->left->right = new Node(3); |
| 257 | + root->right->left = new Node(5); |
| 258 | + root->right->right = new Node(7); |
| 259 | + |
| 260 | + // Convert BST to Min Heap |
| 261 | + BST_to_MinHeap(root); |
| 262 | + |
| 263 | + // Print the tree in preorder to verify Min Heap property |
| 264 | + cout << "Preorder of Min Heap : "; |
| 265 | + print(root); |
| 266 | + cout << endl; |
| 267 | + |
| 268 | + return 0; |
| 269 | +} |
| 270 | +``` |
| 271 | +- **Main Function**: |
| 272 | + - A simple **BST** is constructed manually using `Node` objects. |
| 273 | + - The `BST_to_MinHeap` function is called to convert the BST into a Min Heap. |
| 274 | + - The `print` function is used to print the tree in preorder to verify the Min Heap property. |
| 275 | + |
| 276 | +### Step 3: Example Walkthrough |
| 277 | + |
| 278 | +#### Example 1: |
| 279 | + |
| 280 | +**Input BST**: |
| 281 | +``` |
| 282 | + 4 |
| 283 | + / \ |
| 284 | + 2 6 |
| 285 | + / \ / \ |
| 286 | + 1 3 5 7 |
| 287 | +``` |
| 288 | + |
| 289 | +**Inorder Traversal**: `[1, 2, 3, 4, 5, 6, 7]` |
| 290 | + |
| 291 | +After converting to a Min Heap: |
| 292 | + |
| 293 | +**Min Heap**: |
| 294 | +``` |
| 295 | + 1 |
| 296 | + / \ |
| 297 | + 2 3 |
| 298 | + / \ / \ |
| 299 | + 4 5 6 7 |
| 300 | +``` |
| 301 | + |
| 302 | +**Preorder of Min Heap**: `1 2 4 5 3 6 7` |
| 303 | + |
| 304 | +#### Example 2: |
| 305 | + |
| 306 | +For an empty tree, the output will be: |
| 307 | +``` |
| 308 | +Empty Tree |
| 309 | +``` |
| 310 | + |
| 311 | +### Step 4: Time and Space Complexity |
| 312 | + |
| 313 | +- **Time Complexity**: |
| 314 | + - **Inorder Traversal (`inOrder`)**: This takes **O(n)** time, where `n` is the number of nodes in the tree. |
| 315 | + - **Preorder Traversal (`inOrderToMinHeap`)**: This also takes **O(n)** time as it visits each node once. |
| 316 | + - **Overall Time Complexity**: **O(n)**, where `n` is the number of nodes in the BST. |
| 317 | + |
| 318 | +- **Space Complexity**: |
| 319 | + - **Auxiliary Space**: |
| 320 | + - The `nodes` vector stores `n` elements, so it requires **O(n)** space. |
| 321 | + - The recursion stack also takes **O(h)** space, where `h` is the height of the tree. |
| 322 | + - **Overall Space Complexity**: **O(n)**, considering the storage for the nodes and recursion stack. |
| 323 | + |
| 324 | +### Step 5: Additional Recommendations for Students |
| 325 | + |
| 326 | +- **Understanding Recursion**: Recursion is key to both the inorder and preorder traversals. Understanding how recursion works will help in other tree-based problems as well. |
| 327 | +- **Practice with Other Tree Transformations**: Try solving similar problems, such as converting a **BST to a max-heap** or **flattening a binary tree** into a linked list. |
| 328 | +- **Edge Cases**: Always test edge cases, such as an empty tree or a tree with only one node, to ensure your solution works in all scenarios. |
0 commit comments