-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathLinkedlisttree.cpp
150 lines (138 loc) · 2.86 KB
/
Linkedlisttree.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*Given a binary tree as input, output it as the linkedlist in-place.
The "Linkedlist" should be in the same order as "Preorder Traversal" of the given binary tree.
*/
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
};
TreeNode *node(int val)
{
TreeNode *c = new TreeNode;
c->val = val;
c->left = c->right = NULL;
return c;
}
/*Here,flatten is defined as the function to convert binary tree to linkedlist by altering the left node and making the right node point to null.*/
TreeNode *flatten(TreeNode *A)
{
//if the tree is empty
if (A == NULL)
{
return A;
}
//for the case of leaf node
if (A->left == NULL && A->right == NULL)
{
return A;
}
if (A->right != NULL && A->left == NULL)
{
A->right = flatten(A->right);
return A;
}
else
{
TreeNode *j = A;
TreeNode *p = j->right;
TreeNode *q = j->left;
while (q->right != NULL)
{
q = q->right;
}
q->right = p;
j->right = flatten(j->left);
j->left = NULL;
return j;
}
}
//function for output.
void inorder_output(TreeNode *root)
{
if (root == NULL)
{
return;
}
inorder_output(root->left);
cout << root->val << " ";
inorder_output(root->right);
}
//code for inserting the required value to every node of tree to be formed.
TreeNode *insert_value(TreeNode *root, int val, queue<TreeNode *> &t)
{
TreeNode *temp = node(val);
if (val == -1)
{
temp = NULL;
}
if (root == NULL)
{
root = temp;
}
else if (t.front()->left == NULL)
t.front()->left = temp;
else
{
t.front()->right = temp;
t.pop();
}
t.push(temp);
return root;
}
//code for creating tree
TreeNode *form_tree(vector<int> v)
{
TreeNode *root = NULL;
queue<TreeNode *> t;
for (int i = 0; i < v.size(); i++)
{
root = insert_value(root, v[i], t);
}
return root;
}
int main()
{
int n;
cin >> n;
vector<int> v;
while (n--)
{
int u;
cin >> u;
v.push_back(u);
}
TreeNode *A = form_tree(v);
inorder_output(flatten(A));
}
/*
sample input:
13
6 4 8 2 -1 5 9 -1 -1 -1 -1 -1 -1
given input tree is:-
6
/ \
4 8
/ / \
2 5 9
sample output:
6 4 2 8 5 9
output flattened tree should be like a linkedlist in-place as shown below :-
6
\
4
\
2
\
8
\
5
\
9
CODE COMPLEXITY FOR THE CODE OF FLATTEN FUNCTION :
1.TIME COMPLEXITY- O(N)
2.SPACE COMPLEXITY- O(1)
*/