Skip to content

Commit daff3d9

Browse files
authored
Create README.md
1 parent 645feb3 commit daff3d9

File tree

1 file changed

+187
-0
lines changed

1 file changed

+187
-0
lines changed
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
<h1 align='center'>Flatten - BST - to - Sorted - List</h1>
2+
3+
## Problem Statement
4+
5+
**Problem URL :** [Flatten BST to Sorted List](https://www.geeksforgeeks.org/problems/flatten-bst-to-sorted-list--111950/0)
6+
7+
![image](https://github.com/user-attachments/assets/d1407faf-b1ff-484a-a4fd-cc52cc199310)
8+
![image](https://github.com/user-attachments/assets/76c864cf-4db8-40e9-b88b-c9d1d65cc684)
9+
![image](https://github.com/user-attachments/assets/d4724782-33c2-448d-be5c-f4deb9259421)
10+
11+
## Problem Explanation
12+
Given a Binary Search Tree (BST), the goal is to "flatten" it into a sorted, linked list structure. Specifically:
13+
- Transform the BST so that each node points to the next node in in-order traversal (left to right, smallest to largest).
14+
- The "left" pointers should be set to `NULL`, and each "right" pointer should link to the next node in sorted order.
15+
16+
#### Approach to Solve the Problem
17+
18+
1. **In-Order Traversal**:
19+
- Since an in-order traversal of a BST results in a sorted sequence, we can use it to collect nodes in sorted order.
20+
2. **Rearrange Nodes**:
21+
- Once we have all nodes in a sorted sequence, we can rearrange their pointers to form a linked list structure.
22+
23+
#### Example
24+
25+
Consider the following BST:
26+
```
27+
5
28+
/ \
29+
3 7
30+
/ \ \
31+
2 4 8
32+
```
33+
34+
In-order traversal of this BST gives: `[2, 3, 4, 5, 7, 8]`.
35+
36+
The flattened list will look like:
37+
```
38+
2 -> 3 -> 4 -> 5 -> 7 -> 8 -> NULL
39+
```
40+
## Problem Solution
41+
```cpp
42+
class Solution
43+
{
44+
public:
45+
void inOrder(Node* root, vector<Node*> &nodes){
46+
if(root == NULL) return;
47+
48+
inOrder(root -> left, nodes);
49+
nodes.push_back(root);
50+
inOrder(root -> right, nodes);
51+
}
52+
Node *flattenBST(Node *root)
53+
{
54+
if(root == NULL) return NULL;
55+
56+
vector<Node*> nodes;
57+
inOrder(root, nodes);
58+
59+
Node* newRoot = nodes[0];
60+
Node* current = newRoot;
61+
62+
for(int i = 1; i < nodes.size(); i++){
63+
current -> left = NULL;
64+
current -> right = nodes[i];
65+
current = nodes[i];
66+
}
67+
68+
current -> left = NULL;
69+
current -> right = NULL;
70+
71+
return newRoot;
72+
}
73+
};
74+
```
75+
76+
## Problem Solution Explanation
77+
78+
```cpp
79+
class Solution
80+
{
81+
public:
82+
```
83+
- Defines a `Solution` class with public member functions.
84+
85+
```cpp
86+
void inOrder(Node* root, vector<Node*> &nodes){
87+
if(root == NULL) return;
88+
```
89+
- `inOrder` is a helper function that performs an in-order traversal of the BST.
90+
- If the current `root` is `NULL`, the function exits since there's no node to process.
91+
92+
```cpp
93+
inOrder(root -> left, nodes);
94+
nodes.push_back(root);
95+
inOrder(root -> right, nodes);
96+
}
97+
```
98+
- The function recursively traverses the left subtree, adds the current node (`root`) to the `nodes` vector, and then traverses the right subtree.
99+
- This process ensures that nodes are added in sorted order.
100+
101+
```cpp
102+
Node *flattenBST(Node *root)
103+
{
104+
if(root == NULL) return NULL;
105+
```
106+
- `flattenBST` is the main function that initiates the process of flattening the BST.
107+
- If `root` is `NULL`, it returns `NULL` immediately as there's nothing to flatten.
108+
109+
```cpp
110+
vector<Node*> nodes;
111+
inOrder(root, nodes);
112+
```
113+
- Creates an empty vector `nodes` to store BST nodes in sorted order.
114+
- Calls the `inOrder` function to fill `nodes` with the nodes of the BST in sorted order.
115+
116+
```cpp
117+
Node* newRoot = nodes[0];
118+
Node* current = newRoot;
119+
```
120+
- Sets `newRoot` to the first node in `nodes` (smallest value in the BST) to be the new root of the flattened list.
121+
- `current` is a pointer that will help to link each node in the list.
122+
123+
```cpp
124+
for(int i = 1; i < nodes.size(); i++){
125+
current -> left = NULL;
126+
current -> right = nodes[i];
127+
current = nodes[i];
128+
}
129+
```
130+
- Iterates through the remaining nodes in `nodes`.
131+
- For each node:
132+
- Sets the `left` pointer to `NULL` (since we want a single linked list).
133+
- Sets the `right` pointer of `current` to point to the next node in `nodes`.
134+
- Updates `current` to point to the next node.
135+
136+
```cpp
137+
current -> left = NULL;
138+
current -> right = NULL;
139+
```
140+
- Ensures that the last node in the list points to `NULL` for both `left` and `right` pointers.
141+
142+
```cpp
143+
return newRoot;
144+
}
145+
};
146+
```
147+
- Returns `newRoot`, which is the head of the flattened list.
148+
149+
### Step 3: Example Walkthrough
150+
151+
Let's apply the code to the BST:
152+
```
153+
5
154+
/ \
155+
3 7
156+
/ \ \
157+
2 4 8
158+
```
159+
160+
1. **In-Order Traversal**: The `inOrder` function produces a sorted list of nodes in `nodes` as `[2, 3, 4, 5, 7, 8]`.
161+
162+
2. **Flattening Process**:
163+
- `newRoot` is set to `nodes[0]`, which is node `2`.
164+
- The `for` loop iterates through the `nodes` vector, setting up the linked list:
165+
```
166+
2 -> 3 -> 4 -> 5 -> 7 -> 8 -> NULL
167+
```
168+
- The flattened list is returned, starting from `newRoot`, which points to `2`.
169+
170+
### Step 4: Time and Space Complexity
171+
172+
1. **Time Complexity**:
173+
- **In-Order Traversal**: \( O(n) \), where \( n \) is the number of nodes in the BST.
174+
- **Flattening Process**: \( O(n) \) for linking nodes in the sorted order.
175+
- **Total Time Complexity**: \( O(n) + O(n) = O(n) \).
176+
177+
2. **Space Complexity**:
178+
- **Auxiliary Space for Vector**: \( O(n) \) for storing nodes in `nodes`.
179+
- **Recursive Call Stack**: \( O(h) \), where \( h \) is the height of the tree (up to \( O(\log n) \) for balanced BSTs, \( O(n) \) for skewed trees).
180+
- **Total Space Complexity**: \( O(n) \).
181+
182+
### Step 5: Recommendations for Students
183+
184+
- **Practice Recursive Tree Traversals**: Understanding in-order traversal is essential for this solution. Practice it on other trees to get comfortable.
185+
- **Learn About Linked Lists**: Since the output is a linked list, knowing how to manipulate pointers (left and right pointers) will help.
186+
- **Dry-Run the Code on Examples**: Take a small BST, manually run through the code, and verify each step aligns with the explanation.
187+
- **Understand Complexity Analysis**: Being able to calculate time and space complexity is crucial for efficiency in tree problems, especially as trees grow larger.

0 commit comments

Comments
 (0)