Skip to content

Commit 31f7d06

Browse files
committed
Solution as on 29-07-2022 10:00 pm
1 parent f8e65ff commit 31f7d06

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// 114.✅ Flatten Binary Tree to Linked List
2+
3+
class Solution
4+
{
5+
public:
6+
void flatten(TreeNode *root)
7+
{
8+
9+
if (root == nullptr)
10+
return;
11+
12+
stack<TreeNode *> st;
13+
st.push(root);
14+
15+
while (!st.empty())
16+
{
17+
TreeNode *curr = st.top();
18+
st.pop();
19+
if (curr->right)
20+
st.push(curr->right);
21+
if (curr->left)
22+
st.push(curr->left);
23+
if (!st.empty())
24+
curr->right = st.top();
25+
curr->left = nullptr;
26+
}
27+
}
28+
};
29+
30+
// Another Approach
31+
32+
class Solution
33+
{
34+
public:
35+
TreeNode *prev = nullptr;
36+
void flatten(TreeNode *root)
37+
{
38+
if (root == nullptr)
39+
return;
40+
flatten(root->right);
41+
flatten(root->left);
42+
root->right = prev;
43+
root->left = nullptr;
44+
prev = root;
45+
}
46+
};

0 commit comments

Comments
 (0)