This Program is to insert the number entered by the user in the binary tree .
For Example:
Input for tree is: 4,5,7,8,9
The entered element to insert into binary tree is : 6
Output will be :
Element Inserted
After inserting array is : 4,5,6,7,8,9
Program :
//C++ program to insert an element into binary tree#include<bits/stdc++.h>usingnamespacestd;
// tree nodestructNode
{int data;
Node *left, *right;
};
// returns a new tree NodeNode* newNode(int data){
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A function to create binary tree.Node* Tree(Node* temp, int data ){
// If the tree is empty, return a new nodeif (temp == NULL)
return newNode(data);
// Otherwise, recur down the treeif (data < temp->data)
temp->left = Tree(temp->left, data);
else
temp->right = Tree(temp->right, data);
//return the (unchanged) node pointerreturn temp;
}
//function to display all the element present in the binary treevoiddisplay(struct Node* root){
if (!root)
return;
display(root->left);
cout<<root->data<<" ";
display(root->right);
}
//function to insert element in binary treevoidinsert(struct Node* root , int value){
queue<struct Node*> q;
q.push(root);
// Do level order traversal until we find an empty place.while (!q.empty()) {
structNode* 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);
}
}
intmain(){
char ch;
int n, arr[20],size;
Node *root = new Node;
root = NULL;
cout<<"Enter the size of array : ";
cin>>size;
cout<<"Enter the elements in array : ";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
// Construct the binary tree.for(int i = 0; i < size; i++)
{
root = Tree(root, arr[i]);
}
cout<<"\nEnter the Element to be insert : ";
cin>>n;
insert(root,n);
cout<<"\nElement Inserted"<<endl;
cout<<"\nAfter Inserting "<<endl;
cout<<"Elements are: ";
display(root);
cout<<endl;
return0;
}
Comments