-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpracticep60_bst_1.cpp
More file actions
109 lines (94 loc) · 2.46 KB
/
practicep60_bst_1.cpp
File metadata and controls
109 lines (94 loc) · 2.46 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
#include <iostream>
using namespace std;
//Binary search tree
//Insertion
//traversal- IN, POST, PRE.
class Node{
public:
int data;
Node* left;
Node* right;
Node(int data){
this->data=data;
this->left=NULL;
this->right=NULL;
};
};
Node* insert(Node* root, int data) {
// If tree is empty, return a new node
if (root == nullptr) {
Node* newNode=new Node(data);
return newNode;
}
// Otherwise, recur down the tree
if(data==root->data){ //not needed(just to let know user.)
cout<<"Dont enter duplicate data."<<endl;
}
if (data < root->data) {
root->left = insert(root->left, data); // Insert in left subtree
} else if (data > root->data) {
root->right = insert(root->right, data); // Insert in right subtree
}
return root;
};
// Function to perform inorder traversal (left, root, right)
void inorderTraversal(Node* root) {
if (root == nullptr) {
return; // Base case: If the node is null, return
}
inorderTraversal(root->left); // Traverse the left subtree
cout << root->data << " "; // Visit the node
inorderTraversal(root->right); // Traverse the right subtree
};
void postorderTraversal(Node* root){
if(root==NULL){
return;
};
postorderTraversal(root->left);
postorderTraversal(root->right);
cout<<root->data<<" ";
};
void preorderTraversal(Node* root){
if(root==NULL){
return;
};
cout<<root->data<<" "<<"\n";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main(){
Node* root=NULL;
int c;
cout<<"1-INSERT\n2-INORDER TRAVERSAL\n3-POSTORDER TRAVERSAL\n4-PREORDER TRAVERSAL"<<endl;
while(true){
cout<<"Enter choice:";
cin>>c;
switch(c){
case 1:
int d,r,temp;
cout<<"Enter the data: ";
cin>>d;
temp=d;
r=d%10;
if(d%r==0){
root=insert(root,temp);
};
break;
case 2:
cout<<"Inorder traversal: ";
inorderTraversal(root);
cout<<endl;
break;
case 3:
cout<<"Postorder Traversal: ";
postorderTraversal(root);
cout<<endl;
break;
case 4:
cout<<"Preorder Traversal: ";
preorderTraversal(root);
cout<<endl;
break;
}
}
}