-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathinsertioninBT.cpp
More file actions
87 lines (76 loc) · 1.45 KB
/
insertioninBT.cpp
File metadata and controls
87 lines (76 loc) · 1.45 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
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left, *right;
};
Node* newNode(int data){
Node* temp=new Node();
BT->data=data;
BT->left=BT->right=NULL;
return BT;
}
Node* Tree(Node* BT, int data ){
if(BT==NULL){
return newNode(data);
}
if(data<BT->data){
BT->left=Tree(BT->left, data);
}
else{
BT->right=Tree(BT->right, data);
}
return BT;
}
void displayelements(struct Node* root){
if(!root){
return;
}
displayelements(root->left);
cout<<root->data<<" ";
displayelements(root->right);
}
void insertelement(struct Node* root , int value){
queue<struct Node*> q;
q.push(root);
while(!q.empty()) {
struct Node* root = q.front();
q.pop();
if(!root->left) {
root->left = newNode(value);
break;
}
else{
q.push(root->left);
}
if(!root->right){
root->right = newNode(value);
break;
}
else{
q.push(root->right);
}
}
}
int main()
{
char ch;
int size;
cout<<"Enter size of array : ";
cin>>size;
int arr[size];
Node *root = new Node;
root = NULL;
cout<<"Enter elements in array : ";
for(int i=0;i<size;i++){
cin>>arr[i];
}
for(int i = 0; i < size; i++){
root = Tree(root, arr[i]);
}
int n;
cout<<"Enter Element to insert : ";
cin>>n;
insertelement(root,n);
displayelements(root);
}