-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlatten_a_Binary_Tree.cpp
More file actions
96 lines (86 loc) · 1.63 KB
/
Copy pathFlatten_a_Binary_Tree.cpp
File metadata and controls
96 lines (86 loc) · 1.63 KB
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
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
node(int d)
{
data = d;
left = NULL;
right = NULL;
}
};
// root - Root of the Binary Tree
// This function should return the head of the resultant linked list
node *flatten(node *root)
{
if (!root)
return root;
if (!root->left and !root->right)
return root;
node *ll = NULL;
node *l = flatten(root->left);
node *r = flatten(root->right);
if (!l and r)
{
root->right = r;
root->left = NULL;
ll = root;
}
else if (l and !r)
{
ll = l;
node *t = ll;
while (t->right != NULL)
t = t->right;
root->left = NULL;
t->right = root;
}
else
{
ll = l;
node *t = ll;
while (t->right != NULL)
t = t->right;
t->right = root;
root->left = NULL;
root->right = r;
}
return ll;
}
void printLinkedList(node *head)
{
node *temp = head;
while (temp != NULL)
{
if (temp->left != NULL)
{
cout << "Left pointer for node with data=" << temp->data << " is changed to NULL" << endl;
}
cout << temp->data << " ";
temp = temp->right;
}
}
node *buildTree()
{
int d;
cin >> d;
if (d == -1)
{
return NULL;
}
node *root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
int main()
{
node *root = buildTree();
node *head = flatten(root);
printLinkedList(head);
return 0;
}