Uploaded by Tasrif Khan

Final-Term-Assignment

advertisement
Final Term Assignment
Data Structure Lab
Name:
ID:
Section:
Instructions:
Write your name, ID and, section in the given space.
Answer the question in this document.
After completing it, save the file as a pdf and upload it to the portal under the “Final
Assignment” Section.
Submission Deadline: 13/08/2021
Question:
A code is given in Appendix 1. An array is given in the main function. The code for creating a
BST from this array is given. You have to write the code of the inorder function to sort the
given array.
Basic implementation of inorder function is given below:
node * inorder(node *n)
{
if(n==NULL)
{
return NULL;
}
inorder(n->left);
cout<<n->data <<", ";
inorder(n->right);
}
This function can only print the sorted order. Modify this function to sort the given array in
the main function. The function signature is given in the Appendix 1.
Don’t modify any other function except inorder.
If your code is ok then, it should print the following output:
Sorted Output: 1 2 3 4 5 8 9 11 20
Answer
Solve the code and paste the inorder function in the below space:
Appendix 1:
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
};
class BST
{
node *root=NULL;
public:
node * getRoot(){return root;}
void setRoot(node *n){root = n;}
void _insert(int value)
{
node *n = new node;
n->data = value;
n->left = NULL;
n->right = NULL;
if(root==NULL)
{
root = n;
}
else
{
node *temp = root;
while(true)
{
if(temp->data==value)
{
break;
}
else if(temp->data > value)
{
if(temp->left == NULL)
{
temp->left = n;
break;
}
else
{
temp = temp->left;
}
}
else if(temp->data < value)
{
if(temp->right == NULL)
{
temp->right = n;
break;
}
else
{
temp = temp->right;
}
}
}
}
}
node * inorder(node *n, int a[], int *index)
{
//Implement this function to sort the given array in the main function
}
};
int main()
{
int arr[] = { 9, 2, 5, 3, 8, 11, 20, 1, 4};
BST bst;
int i;
for(i=0; i<9; i++)
{
bst._insert(arr[i]);
}
int index = 0;
bst.inorder(bst.getRoot(), arr, &index);
cout<<endl<<"Sorted Output: ";
for(i=0;i<9;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
Download