Thursday, September 20, 2018

C++ Program with output Functions to Construct Binary Search Tree from given Array and Output

//Binary Search Tree Program
#include <iostream>
using namespace std;

//Node
struct Node
{
int data;
Node* left, *right;
}*root = NULL;

// Finding position for the current node and Inserting it
void Insert_In_Tree(Node* ptr, Node* newnode)
{

if (root == NULL)
{
root = newnode;
}

else
{
if (newnode->data <= ptr->data)
{
if (ptr->left == NULL)
{
ptr->left = newnode;
}

else
{
Insert_In_Tree(ptr->left, newnode);
}
}

else
{
if(ptr->right == NULL)
{
ptr->right = newnode;

}

else
{
Insert_In_Tree(ptr->right, newnode);
}
}
}

return;
}


//Node creation for Tree
void MakeNode(int arr[], int size)
{
Node *newnode;
for (int i = 0; i < size; i++)
{
newnode = new Node;
newnode->data=arr[i];
newnode->left = newnode->right = NULL;
Insert_In_Tree(root, newnode);
}

}

//Simple Binary Tree Traversal Functions.
void preorder(Node *ptr)
{
if (ptr==NULL)
{
return;
}
else
{
cout<<ptr->data<<" ";
preorder(ptr->left);
preorder(ptr->right);
}
}

void Inorder(Node *ptr)
{
if(ptr==NULL)
{
return;
}
else
{
Inorder(ptr->left);
cout<<ptr->data<<" ";
Inorder(ptr->right);
}
}

void Post_order(Node *ptr)
{
if(ptr==NULL)
{
return;
}
else
{
Post_order(ptr->left);
Post_order(ptr->right);
cout<<ptr->data<<" ";
}
}

int main()
{
int size;

cout<<"\n Enter the size of the array : ";
cin>>size;
int arr[size];
cout<<"\n Enter the elements in the array : ";
for (int i = 0; i < size; i++)
cin>>arr[i];
MakeNode(arr,size);

cout<<"\n Preorder : ";
preorder(root);
cout<<"\n Inorder : ";
Inorder(root);
cout<<"\n Post Order : ";
Post_order(root);
cout<<"\n";

return 0;
}



No comments:

Post a Comment