-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCTree.cpp
More file actions
134 lines (126 loc) · 2.27 KB
/
CTree.cpp
File metadata and controls
134 lines (126 loc) · 2.27 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
/*
* C++ Program To Implement Cartesian Tree
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int data;
struct node* left;
struct node* right;
};
/*
* Class Declaration
*/
class CTree
{
public:
node *newNode (int);
int mini(int [], int, int);
node *buildTree (int [], int, int);
void printInorder (node* node);
void display(node *, int);
CTree()
{}
};
/*
* Main Contains Menu
*/
int main()
{
CTree ct;
int i, n;
cout<<"Enter number of elements to be inserted: ";
cin>>n;
int a[n];
for(i = 0;i < n;i++)
{
cout<<"Enter Element "<<i + 1<<" : ";
cin>>a[i];
}
node *root = ct.buildTree(a, 0, n - 1);
cout<<"Cartesian tree Structure: "<<endl;
ct.display(root,1);
cout<<endl;
cout<<"\n Inorder traversal of the constructed tree \n"<<endl;
ct.printInorder(root);
cout<<endl;
return 0;
}
/*
* Creating New Node
*/
node *CTree::newNode (int data)
{
node* temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/*
* Finding index of minimum element
*/
int CTree::mini(int arr[], int strt, int end)
{
int i, min = arr[strt], minind = strt;
for(i = strt + 1; i <= end; i++)
{
if(arr[i] < min)
{
min = arr[i];
minind = i;
}
}
return minind;
}
/*
* Function for Building Tree
*/
node *CTree::buildTree (int inorder[], int start, int end)
{
if (start > end)
return NULL;
int i = mini(inorder, start, end);
node *root = newNode(inorder[i]);
if (start == end)
return root;
root->left = buildTree(inorder, start, i - 1);
root->right = buildTree(inorder, i + 1, end);
return root;
}
/*
* InOrder Traversal
*/
void CTree::printInorder (struct node* node)
{
if (node == NULL)
return;
printInorder (node->left);
cout<<node->data<<" ";
printInorder (node->right);
}
/*
* Display Tree
*/
void CTree::display(node *ptr, int level)
{
int i;
if(ptr == NULL)
return;
if (ptr != NULL)
{
display(ptr->right, level + 1);
cout<<endl;
for (i = 0;i < level;i++)
cout<<" ";
cout<<ptr->data;
display(ptr->left, level + 1);
}
}
//11 8 4 9 3 5 0 11 2 6 7 12