-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTree.cpp
More file actions
96 lines (96 loc) · 1.58 KB
/
Tree.cpp
File metadata and controls
96 lines (96 loc) · 1.58 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 <iostream>
using namespace std;
class Node
{
int data;
Node* left=NULL;
Node* right=NULL;
public:
Node() {
};
void sdata(int adata){
data=adata;
};
void sleft(Node* aleft){
left=aleft;
};
void sright(Node* aright){
right=aright;
}
int Data(){
return data;
};
Node* Left(){
return left;
};
Node* Right(){
return right;
};
};
class Tree
{
Node* root=NULL;
public:
Tree(){
};
void insertnode(Node* node, int data);
void printtree(Node* root);
};
void Tree::insertnode(Node* node, int data)
{
if(node->Data()<data)
{
if(node->Left()!=NULL)
insertnode(node->Left(),data);
else
{
Node* newnode = new Node();
newnode->sdata(data);
node->sleft(newnode);
}
}
else
{
if(node->Right()!=NULL)
insertnode(node->Right(),data);
else
{
Node* newnode = new Node();
newnode->sdata(data);
node->sright(newnode);
}
}
}
void printtree(Node* root)
{
if(root==NULL)
return;
printtree(root->Right());
cout<<root->Data();
printtree(root->Left());
}
int main()
{
Tree tree;
int data,n;
Node* root=NULL;
while(n!=3){
cout<<"(1) Insert into tree\n(2) Print the tree\n";
cout<<"(3) Exit\n";
cin>>n;
switch(n)
{
case 1:cout<<"Enter element to be inserted\n";
cin>>data;
tree.insertnode(root,data);
break;
case 2:tree.printtree(root);
break;
case 3:cout<<"Exiting...\n";
break;
default:cout<<"Invalid option\n";
break;
}
}
return 0;
}