|
| 1 | +<h1 align='center'>Search - a Node - In - BST</h1> |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +**Problem URL :** [Search a Node in BST](https://www.geeksforgeeks.org/problems/search-a-node-in-bst/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card) |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +## Problem Explanation |
| 11 | +In this problem, you're given a Binary Search Tree (BST) and a target value. You need to determine whether this target value is present in the BST. |
| 12 | + |
| 13 | +A **BST** is a binary tree where each node follows these properties: |
| 14 | +1. All values in the left subtree are smaller than the node's value. |
| 15 | +2. All values in the right subtree are larger than the node's value. |
| 16 | + |
| 17 | +#### Objective |
| 18 | +If the target value exists in the BST, the function should return `true`; otherwise, it should return `false`. |
| 19 | + |
| 20 | +#### Constraints |
| 21 | +1. The tree may be empty. |
| 22 | +2. Node values are unique. |
| 23 | +3. Each node only contains integer values. |
| 24 | + |
| 25 | +#### Example |
| 26 | +Given the following BST: |
| 27 | + |
| 28 | +``` |
| 29 | + 10 |
| 30 | + / \ |
| 31 | + 5 15 |
| 32 | + / \ \ |
| 33 | + 2 7 20 |
| 34 | +``` |
| 35 | + |
| 36 | +- If the target value is `7`, the function should return `true` because `7` is present in the tree. |
| 37 | +- If the target value is `12`, the function should return `false` because `12` is not present in the tree. |
| 38 | + |
| 39 | +#### Real-world Analogy |
| 40 | +Imagine the BST as a bookshelf organized by book titles in alphabetical order. If you want to find a particular book, you can quickly decide whether to search to the left (earlier titles) or right (later titles) without checking every book. Similarly, we can efficiently locate a value in a BST. |
| 41 | + |
| 42 | +#### Edge Cases |
| 43 | +1. **Empty Tree**: If the tree is empty, the target value can’t be found, so the function should return `false`. |
| 44 | +2. **Single Node Tree**: If the tree has only one node, return `true` if the target matches the node’s value; otherwise, return `false`. |
| 45 | +3. **Value Not in Tree**: The target value may not be present in the tree, so the function should handle this gracefully. |
| 46 | + |
| 47 | +--- |
| 48 | + |
| 49 | +### Step 2: Approach |
| 50 | + |
| 51 | +#### High-Level Overview |
| 52 | +Since the tree is a **Binary Search Tree**, we can take advantage of its sorted property. Starting from the root: |
| 53 | +1. If the current node's value matches the target, return `true`. |
| 54 | +2. If the target is smaller than the current node’s value, recursively search the left subtree. |
| 55 | +3. If the target is larger, recursively search the right subtree. |
| 56 | + |
| 57 | +This approach is more efficient than a linear search because each step cuts down the possible nodes by half (similar to binary search). |
| 58 | + |
| 59 | +#### Step-by-Step Breakdown |
| 60 | +1. **Check the Root**: Start at the root node. If it’s `NULL`, return `false` (tree is empty). |
| 61 | +2. **Compare with Root Value**: |
| 62 | + - If the root’s value is equal to the target, return `true`. |
| 63 | + - If the root’s value is less than the target, search in the right subtree. |
| 64 | + - If the root’s value is greater than the target, search in the left subtree. |
| 65 | +3. **Recursively Search**: Continue until the target value is found or the subtree becomes `NULL`. |
| 66 | + |
| 67 | + |
| 68 | +## Problem Solution |
| 69 | +```cpp |
| 70 | +bool present(Node* root, int value){ |
| 71 | + if(root == NULL) return false; |
| 72 | + |
| 73 | + if(root -> data == value) return true; |
| 74 | + |
| 75 | + |
| 76 | + if(root -> data < value) return present(root -> right, value); |
| 77 | + else return present(root -> left, value); |
| 78 | + |
| 79 | + |
| 80 | + return false; |
| 81 | +} |
| 82 | +bool search(Node* root, int x) { |
| 83 | + return present(root, x); |
| 84 | +} |
| 85 | +``` |
| 86 | +
|
| 87 | +## Problem Solution Explanation |
| 88 | +Certainly! Let's go through each line of the source code in detail. |
| 89 | +
|
| 90 | +1. **Function Declaration: `present`** |
| 91 | + ```cpp |
| 92 | + bool present(Node* root, int value) { |
| 93 | + ``` |
| 94 | + - This line declares a helper function `present` that takes two arguments: |
| 95 | + - `Node* root`: A pointer to the root node of the BST (or subtree). |
| 96 | + - `int value`: The integer value that we are searching for. |
| 97 | + - The function returns a boolean (`true` or `false`) indicating whether the target value exists in the tree. |
| 98 | + |
| 99 | +2. **Check if the Node is `NULL`** |
| 100 | + ```cpp |
| 101 | + if(root == NULL) |
| 102 | + return false; |
| 103 | + ``` |
| 104 | + - This `if` statement checks if the `root` node is `NULL`. |
| 105 | + - If it’s `NULL`, it means we have reached the end of a branch without finding the target value. |
| 106 | + - In this case, the function returns `false` to indicate that the value is not present in the tree. |
| 107 | + |
| 108 | +3. **Check if the Node's Data Matches the Target Value** |
| 109 | + ```cpp |
| 110 | + if(root->data == value) |
| 111 | + return true; |
| 112 | + ``` |
| 113 | + - This line checks if the data in the current `root` node is equal to the `value` we’re searching for. |
| 114 | + - If they are equal, it means we have found the target value in the tree. |
| 115 | + - The function returns `true` to indicate that the target value is present. |
| 116 | + |
| 117 | +4. **Decision to Search Right or Left Subtree** |
| 118 | + ```cpp |
| 119 | + if(root->data < value) |
| 120 | + return present(root->right, value); |
| 121 | + else |
| 122 | + return present(root->left, value); |
| 123 | + ``` |
| 124 | + - **Condition `root->data < value`**: |
| 125 | + - This checks if the current node’s data is less than the target `value`. |
| 126 | + - Since this is a BST, if the current data is less than the target, we only need to search in the **right subtree** (as all larger values are on the right). |
| 127 | + - The function calls itself recursively on the right subtree (`root->right`), with the same target `value`. |
| 128 | + - `return present(root->right, value);` is a recursive call, meaning the function will continue searching down the right branch until it either finds the value or reaches a `NULL` node. |
| 129 | + |
| 130 | + - **`else` Condition**: |
| 131 | + - If the current node’s data is **greater than** the target `value`, we search in the **left subtree** (as all smaller values are on the left). |
| 132 | + - The function calls itself recursively on the left subtree (`root->left`) with the target `value`. |
| 133 | + - `return present(root->left, value);` continues the search down the left branch of the tree. |
| 134 | + |
| 135 | +5. **Redundant `return false;` Line (Safeguard)** |
| 136 | + ```cpp |
| 137 | + return false; |
| 138 | + ``` |
| 139 | + - This line is technically redundant because all possible cases (matching, left, and right subtree) have already been handled. |
| 140 | + - However, it's kept as a safeguard to ensure that the function has a return statement in all code paths, even though it won't be reached. |
| 141 | + |
| 142 | +6. **Function Declaration: `search`** |
| 143 | + ```cpp |
| 144 | + bool search(Node* root, int x) { |
| 145 | + ``` |
| 146 | + - This line declares the main function `search`, which serves as an entry point for the search functionality. |
| 147 | + - It takes two parameters: |
| 148 | + - `Node* root`: A pointer to the root node of the entire BST. |
| 149 | + - `int x`: The integer value to search for in the BST. |
| 150 | + - This function returns a boolean indicating whether the value `x` exists in the tree. |
| 151 | +
|
| 152 | +7. **Calling the Helper Function `present`** |
| 153 | + ```cpp |
| 154 | + return present(root, x); |
| 155 | + ``` |
| 156 | + - This line calls the `present` function, passing it the root node and the target value `x`. |
| 157 | + - It simply returns whatever result `present` produces—either `true` (if the value is found) or `false` (if it isn’t). |
| 158 | + - This function is essentially a wrapper around the `present` function to keep the interface simple for calling code. |
| 159 | + |
| 160 | +### Summary of Code Execution |
| 161 | + |
| 162 | +- The `search` function is the main entry point. It calls `present`, which performs a recursive search through the BST. |
| 163 | +- The `present` function uses the properties of the BST to quickly locate or discard branches, making the search efficient. |
| 164 | +- If the target value is found at any node, the function immediately returns `true`. |
| 165 | +- If the search reaches the end of a branch (`NULL`), it returns `false`, indicating the value isn’t in the tree. |
| 166 | + |
| 167 | + |
| 168 | +### Example Output |
| 169 | + |
| 170 | +Let’s add some example outputs to see the function in action: |
| 171 | + |
| 172 | +1. **Example 1**: |
| 173 | + - **Input**: `search(root, 7)` |
| 174 | + - **Output**: `true` |
| 175 | + - **Explanation**: The value `7` is in the BST, so the function returns `true`. |
| 176 | + |
| 177 | +2. **Example 2**: |
| 178 | + - **Input**: `search(root, 12)` |
| 179 | + - **Output**: `false` |
| 180 | + - **Explanation**: The value `12` is not in the BST, so the function returns `false`. |
| 181 | + |
| 182 | +3. **Example 3**: |
| 183 | + - **Input**: `search(root, 10)` |
| 184 | + - **Output**: `true` |
| 185 | + - **Explanation**: The root node itself contains the value `10`, so the function returns `true` immediately. |
| 186 | + |
| 187 | +This breakdown should help beginners understand how the recursive search works in a BST, along with the code structure and execution flow. |
| 188 | + |
| 189 | +### Step 5: Time and Space Complexity |
| 190 | + |
| 191 | +#### Time Complexity |
| 192 | +- **Average Case**: \( O(\log N) \) because each recursive call halves the remaining nodes by choosing either the left or right subtree, similar to binary search. |
| 193 | +- **Worst Case**: \( O(N) \), which happens when the tree is skewed (like a linked list). |
| 194 | + |
| 195 | +### Summary |
| 196 | +- The `search` function checks if a given value exists in a BST by leveraging its properties. |
| 197 | +- The solution is efficient for balanced BSTs but can be slower for skewed trees. |
| 198 | +- **Best Practices**: Always check if the tree is balanced or apply balancing techniques (like AVL or Red-Black Trees) for consistent \( O(\log N) \) performance. |
0 commit comments