-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem-114.cpp
57 lines (50 loc) · 1.31 KB
/
Problem-114.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Problem - 114
// https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
// O(n) time complexity and O(n) space complexity solution using stack
class Solution {
public:
void flatten(TreeNode* root) {
if(!root)
return;
stack <TreeNode*> s;
s.push(root);
TreeNode* prev = NULL;
while(!s.empty()) {
auto curr = s.top();
s.pop();
if(curr->right) {
s.push(curr->right);
}
if(curr->left) {
s.push(curr->left);
}
if(prev) {
prev->right = curr;
prev->left = NULL;
}
prev = curr;
}
}
};
// OR
// O(n) time complexity and O(1) space complexity solution
class Solution {
public:
void flatten(TreeNode* root) {
if(!root)
return;
TreeNode* curr = root;
while(curr) {
if(curr->left) {
TreeNode* temp = curr->left;
while(temp->right) {
temp = temp->right;
}
temp->right = curr->right;
curr->right = curr->left;
curr->left = NULL;
}
curr = curr->right;
}
}
};