-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathswap_nodes.cpp
94 lines (71 loc) · 1.15 KB
/
swap_nodes.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
#include<iostream>
#include<queue>
using namespace std;
struct node{
int data;
node *left;
node *right;
node(int k)
{
data=k;
left=NULL;
right=NULL;
}
};
node* addnode()
{
queue<node*> q;
int n,k;
node* root;
cin>>n; //n defines the number of nodes
while(n--)
{
cin>>k; //data value of the node
node* a = new node(k);
if(!q.empty())
{
if(q.front()->left==NULL)
{
q.front()->left=a;
}
else if(q.front()->right==NULL)
{
q.front()->right=a;
q.pop();
}
}
else
{
root=a;
}
q.push(a);
}
return root;
}
node * swap(node * root)
{
if(root==NULL)
return NULL;
node * temp;
temp=root->left;
root->left=root->right;
root->right = temp;
swap(root->left);
swap(root->right);
return root;
}
void print(node * root)
{
if(root==NULL)
return;
cout<<root->data<<" ";
print(root->left);
print(root->right);
}
int main()
{
node* root=addnode();
root=swap(root);
print(root);
return 0;
}