-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinary_Tree_Traversal_2.cpp
More file actions
134 lines (121 loc) · 2.84 KB
/
Copy pathBinary_Tree_Traversal_2.cpp
File metadata and controls
134 lines (121 loc) · 2.84 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
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
/*
PRIYANSHU IS A PEACEFULL SOUL
*/
#include <bits/stdc++.h>
#define vi vector<int>
#define vvi vector<vi>
#define pii pair<int,int>
#define vii vector<pii>
#define rep(i,a,b) for(int i=a;i<b;i++)
#define ff first
#define ll long long
#define ss second
using namespace std;
class node{
public:
int data;
node *left;
node *right;
node(int val){
data = val;
left = NULL;
right = NULL;
}
};
node * rt = NULL;
bool searchNode(node *root, int value){
node *tmp = root;
if (tmp == NULL){
return false;
}
if (tmp->data == value){
rt = tmp;
return true;
}
bool is_left = searchNode(tmp->left, value);
if (is_left)
return true;
bool is_right = searchNode(tmp->right, value);
if (is_right)
return true;
return false;
}
void insertNode(node *root, int ro, int le, int ri){
bool v = searchNode(root, ro);
bool l = searchNode(root,le);
bool r = searchNode(root,ri);
if (v == true){
if (l && le!=0){
cout << "Left node is already a child node" << endl;
exit(0);
}
else if (r && ri!=0){
cout << "Right node is already a child node" << endl;
exit(0);
}
else{
if(ri!=0){
rt->right = new node(ri);
}
if(le!=0){
rt->left = new node(le);
}
}
}
}
void inorder(node*root){if(root==NULL){
return;
}
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
void preorder(node*root){
if(root==NULL){
return;
}
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
void postorder(node*root){
if(root==NULL){
return;
}
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
int main()
{
int nodenum;
cin >> nodenum;
int rootval, leftval, rightval;
cin >> rootval >> leftval >> rightval;
node *root = new node(rootval);
root->left = new node(leftval);
root->right = new node(rightval);
if (rootval == leftval || rightval == rootval){
cout << "Tree can not contain loop";
exit(0);
}
for (int i = 1; i < nodenum; i++){
cin >> rootval >> leftval >> rightval;
if (leftval == 0 && rightval == 0){
continue;
}
else if (rootval == leftval || rootval==rightval){
cout << "Tree can not contain loop";
exit(0);
}
else{
insertNode(root, rootval, leftval, rightval);
}
}
preorder(root);
cout << endl;
inorder(root);
cout << endl;
postorder(root);
return 0;
}