|
| 1 | +<h1 align='center'>Lowest - Common - Ancestor - In a - BST</h1> |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +**Problem URL :** [Lowest Common Ancestor in a BST](https://www.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card) |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +## Problem Explanation |
| 11 | +The **Lowest Common Ancestor (LCA)** in a Binary Search Tree (BST) is defined as the deepest node that is an ancestor to both of the given nodes. In simpler terms, it is the lowest node in the tree that is a parent to both nodes. |
| 12 | + |
| 13 | +#### Understanding the BST |
| 14 | +A Binary Search Tree is a special kind of binary tree where: |
| 15 | +- The left subtree of a node contains only nodes with values less than the node's value. |
| 16 | +- The right subtree of a node contains only nodes with values greater than the node's value. |
| 17 | +- The left and right subtree must also be binary search trees. |
| 18 | + |
| 19 | +#### Example: |
| 20 | +Consider the following BST: |
| 21 | + |
| 22 | +``` |
| 23 | + 20 |
| 24 | + / \ |
| 25 | + 10 30 |
| 26 | + / \ / \ |
| 27 | + 5 15 25 35 |
| 28 | +``` |
| 29 | + |
| 30 | +**Example 1:** |
| 31 | +- If we want to find the LCA of nodes `5` and `15`: |
| 32 | + - Start at `20`, both `5` and `15` are in the left subtree, so move to `10`. |
| 33 | + - At `10`, `5` is in the left subtree and `15` is in the right subtree, making `10` the LCA. |
| 34 | + |
| 35 | +**Example 2:** |
| 36 | +- If we want to find the LCA of nodes `5` and `30`: |
| 37 | + - Start at `20`, move to the left (5 is in the left subtree) and to the right (30 is in the right subtree). |
| 38 | + - Since `20` is the first node where the paths to `5` and `30` diverge, `20` is the LCA. |
| 39 | + |
| 40 | +#### Why is Finding the LCA Important? |
| 41 | +Finding the LCA is crucial in various applications, such as: |
| 42 | +- Understanding hierarchical relationships in trees (family trees, organizational structures). |
| 43 | +- Efficiently querying relationships between nodes in a tree structure. |
| 44 | + |
| 45 | +## Problem Solution |
| 46 | +```cpp |
| 47 | +class Solution{ |
| 48 | + public: |
| 49 | + Node* LCA(Node *root, int n1, int n2) |
| 50 | + { |
| 51 | + if(root == NULL) return NULL; |
| 52 | + |
| 53 | + while(root != NULL){ |
| 54 | + if(root -> data < n1 && root -> data < n2){ |
| 55 | + root = root -> right; |
| 56 | + } |
| 57 | + |
| 58 | + else if(root -> data > n1 && root -> data > n2){ |
| 59 | + root = root -> left; |
| 60 | + } |
| 61 | + |
| 62 | + else return root; |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | +}; |
| 69 | +``` |
| 70 | + |
| 71 | +## Problem Solution Explanation |
| 72 | +Let's refine the code explanation to make it clearer and more structured, focusing on a simple and straightforward breakdown of each part of the code. |
| 73 | + |
| 74 | +1. **Class Declaration:** |
| 75 | + ```cpp |
| 76 | + class Solution { |
| 77 | + ``` |
| 78 | + - This defines a class named `Solution`, which will contain our function to find the LCA. |
| 79 | +
|
| 80 | +2. **Function Declaration:** |
| 81 | + ```cpp |
| 82 | + public: |
| 83 | + Node* LCA(Node *root, int n1, int n2) { |
| 84 | + ``` |
| 85 | + - This is the declaration of the `LCA` function. It takes three parameters: |
| 86 | + - `Node *root`: The root of the BST. |
| 87 | + - `int n1`: The value of the first node. |
| 88 | + - `int n2`: The value of the second node. |
| 89 | + - It returns a pointer to the `Node` that is the LCA of `n1` and `n2`. |
| 90 | + |
| 91 | +3. **Check for Empty Tree:** |
| 92 | + ```cpp |
| 93 | + if (root == NULL) return NULL; // Check if the tree is empty |
| 94 | + ``` |
| 95 | + - If the `root` is `NULL`, it means the tree is empty, so we return `NULL`. |
| 96 | + |
| 97 | +4. **Traverse the Tree:** |
| 98 | + ```cpp |
| 99 | + while (root != NULL) { // Traverse the tree |
| 100 | + ``` |
| 101 | + - We enter a `while` loop that continues until `root` becomes `NULL`. |
| 102 | +
|
| 103 | +5. **Both Nodes on the Right:** |
| 104 | + ```cpp |
| 105 | + if (root->data < n1 && root->data < n2) { // Both nodes are on the right |
| 106 | + root = root->right; // Move to the right child |
| 107 | + ``` |
| 108 | + - If both `n1` and `n2` are greater than the current `root` value, it means both nodes are located in the right subtree. Therefore, we move `root` to its right child. |
| 109 | + |
| 110 | +6. **Both Nodes on the Left:** |
| 111 | + ```cpp |
| 112 | + else if (root->data > n1 && root->data > n2) { // Both nodes are on the left |
| 113 | + root = root->left; // Move to the left child |
| 114 | + ``` |
| 115 | + - If both `n1` and `n2` are less than the current `root` value, both nodes are in the left subtree. We move `root` to its left child. |
| 116 | +
|
| 117 | +7. **Found the LCA:** |
| 118 | + ```cpp |
| 119 | + else { // We found the split point |
| 120 | + return root; // This is the LCA |
| 121 | + } |
| 122 | + ``` |
| 123 | + - If neither of the above conditions is true, it means we have found the split point where one node is on one side and the other node is on the opposite side. Hence, `root` is the LCA, and we return it. |
| 124 | + |
| 125 | +8. **Return NULL (Not Needed):** |
| 126 | + ```cpp |
| 127 | + return NULL; // In case no LCA is found, though it shouldn't reach here |
| 128 | + ``` |
| 129 | + - This line is technically unreachable in the context of a valid BST containing both nodes. It's a safety net but won't be executed. |
| 130 | + |
| 131 | +### Step 3: Examples and Their Explanation |
| 132 | + |
| 133 | +**Example 1:** |
| 134 | +- **Input:** `n1 = 5`, `n2 = 15` |
| 135 | +- **Output:** `10` |
| 136 | +- **Explanation:** The algorithm starts at `20`, moves to `10`, finds that `5` is in the left subtree and `15` in the right, so it returns `10`. |
| 137 | + |
| 138 | +**Example 2:** |
| 139 | +- **Input:** `n1 = 5`, `n2 = 30` |
| 140 | +- **Output:** `20` |
| 141 | +- **Explanation:** The algorithm starts at `20`, since `5` is on the left and `30` is on the right, it returns `20`. |
| 142 | + |
| 143 | +**Example 3:** |
| 144 | +- **Input:** `n1 = 25`, `n2 = 35` |
| 145 | +- **Output:** `30` |
| 146 | +- **Explanation:** The algorithm starts at `20`, moves to `30`, and finds that both `25` and `35` are on either side, returning `30` as the LCA. |
| 147 | + |
| 148 | +### Step 4: Time and Space Complexity |
| 149 | + |
| 150 | +**Time Complexity:** |
| 151 | +- The time complexity of this approach is **O(h)**, where **h** is the height of the BST. In the worst case (for a skewed tree), this could be **O(n)**, where **n** is the number of nodes in the tree. |
| 152 | + |
| 153 | +**Space Complexity:** |
| 154 | +- The space complexity is **O(1)** because we are using a constant amount of space for variables. We are not using any additional data structures like arrays or lists. |
| 155 | + |
| 156 | +**How Complexity is Calculated:** |
| 157 | +- **Time Complexity Calculation:** |
| 158 | + - The algorithm traverses down the height of the tree to find the LCA, which directly correlates to the height of the tree. |
| 159 | +- **Space Complexity Calculation:** |
| 160 | + - Since there are no recursive calls (it’s an iterative solution) and we are only using a few variables to hold references, the space is constant. |
| 161 | + |
| 162 | +### Step 5: Additional Recommendations |
| 163 | + |
| 164 | +- **Practice:** Encourage students to practice implementing the LCA function on their own with different BSTs to reinforce their understanding. |
| 165 | +- **Explore Variants:** Suggest looking into problems that require finding LCA in different types of trees, such as general trees or binary trees without the BST property. |
| 166 | +- **Resources:** Recommend using platforms like [GeeksforGeeks](https://www.geeksforgeeks.org/) and [LeetCode](https://leetcode.com/) for more practice problems related to trees. |
| 167 | +- **Understanding Edge Cases:** Remind students to consider edge cases, such as when `n1` or `n2` are equal, when both are the same node, or when one of them is the root. |
| 168 | +- **Visualize:** Encourage students to draw the BST and trace the algorithm's steps visually to better understand the traversal path. |
| 169 | + |
| 170 | +By following this structured approach, students will not only learn how to find the LCA in a BST but also gain insights into problem-solving strategies that can be applied to other tree-related problems. |
0 commit comments