-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtreeTraversal.cpp
More file actions
124 lines (120 loc) · 2.52 KB
/
Copy pathtreeTraversal.cpp
File metadata and controls
124 lines (120 loc) · 2.52 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
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
};
Node *CreatenewNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void insert_node(Node *root, int number, int leftvalue, int rightvalue)
{
if (root == NULL)
return;
if (root->data == number)
{
root->left = CreatenewNode(leftvalue);
root->right = CreatenewNode(rightvalue);
}
else
{
insert_node(root->left, number, leftvalue, rightvalue);
insert_node(root->right, number, leftvalue, rightvalue);
}
}
void preorder(Node *root)
{
if(root)
{
if(root->data)
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
}
void inorder(Node *root)
{
if(root)
{
inorder(root->left);
if(root->data)
cout<<root->data<<" ";
inorder(root->right);
}
}
void postorder(Node *root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
if(root->data)
cout<<root->data<<" ";
}
}
int main()
{
Node *root = NULL;
int n, i = 0;
cin>>n;
if (n > 20)
exit(0);
int ro[n], l[n], r[n];
while (n--)
{
int number, left, right;
cin>>number>>left>>right;
for (int j = 0; j < i; j++)
{
if (ro[j] == number)
{
cout<<"Tree can not contain loop";
exit(0);
}
if (l[j] == left && left != 0)
{
cout<<"left node is already a child node";
exit(0);
}
if (r[j] == right && right != 0)
{
cout<<"Right node is already a child node";
exit(0);
}
}
ro[i] = number;
l[i] = left;
r[i] = right;
for (int j = 0; j <= i; j++)
{
if (ro[j] == left || ro[j] == right)
{
cout<<"Tree can not contain loop";
exit(0);
}
}
if (root == NULL)
{
root = CreatenewNode(number);
root->left = CreatenewNode(left);
root->right = CreatenewNode(right);
}
else
insert_node(root, number, left, right);
i++;
}
preorder(root);
cout<<endl;
inorder(root);
cout<<endl;
postorder(root);
return 0;
}