MLH GHW TASK
Build a binary search tree
#include<iostream>
using namespace std;
struct Node{
int data;
struct Node *left,*right;
Node(int val)
{
data=val;
left=NULL;
right=NULL;
}
};
Node *insertBST(Node *root,int val)
{
if(root==NULL)
{
return new Node(val);
}
if(val<root->data)
{
root->left=insertBST(root->left,val);
}
else{
root->right=insertBST(root->right,val);
}
return root;
}
void inorder(Node *root)
{
if(root==NULL)
{
return;
}
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
int main()
{
int data,i,n;
Node *root=NULL;
cout<<"Enter number of elements:"<<endl;
cin>>n;
cout<<"Enter the root node:"<<endl;
cin>>data;
root=insertBST(root,data);
cout<<"Enter the remaining elements:"<<endl;
for(i=0;i<n-1;i++)
{
cin>>data;
insertBST(root,data);
}
inorder(root);
return 0;
}
Log in or sign up for Devpost to join the conversation.