Question

Construct a Binary Search Tree (BST) program in C++. The program is required to: 1) load...

Construct a Binary Search Tree (BST) program in C++. The program is required to:

1) load the BST from a dataset (I will provide the datasets-see below) in the order they exist in the dataset.

2) after the BST is built analyze the BST and display the following values:

2.1) the smallest branch height

2.2) the highest branch height

2.3) the number of nodes in the tree

2.4) the determination if the tree is balanced

2.5) the determination if the tree is complete

test file: 15

8

31

42

60

78

77

75

80

88

89

99

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • Below is the C++ program for the BST insertion according to the given dataset in the txt file, and displaying many other information about the BST using many other functions.
  • For better understanding of the code and all functionality please read the comments mentioned in every line and make sure that you keep you dataset in the same directory as that of your cpp(c++) file to get correct output.
  • CODE:

//include all necessary headers.
#include <iostream>
#include <fstream>
using namespace std;

//structure of node of BST(binary search tree).
struct node
{
//data and left right pointers
   int data;
   node * left;
   node * right;
};

//function to create a new node of BST with given data
node *new_node(int data)
{
//create node with given data and set left right pointers to NULL and return node.
   node *temp = new node;
   temp->data = data;
   temp->left = temp->right = NULL;
   return temp;
}

//function to insert a node with given value in current BST with root given as root..
node* insert(struct node* node, int val)
{
   //if tree is empty, return new node with given value.
   if (node == NULL)
{
return new_node(val);
}

   //otherwise find correct position to insert this node down in the tree
   //if val is less than current node's data then recur in left of it
   if(val < node->data)
{
node->left = insert(node->left, val);
}
   else if(val > node->data)
{
node->right = insert(node->right, val);
}
   //return the node which is unchanged
   return node;
}
//function to calculate height of the BST.considering height of single node to be 1..
int height(node*root)
{
//if tree is empty then return 0
if(root==NULL)
{
return 0;
}
//otherwise return 1+ maximum height of left or right subtree.
return 1+max(height(root->left), height(root->right));
}

//function to check is the BST is balanced or not
bool is_balanced(node* root)
{
//if tree is empty then it is balanced.
if (root == NULL)
{
return true;
}

//calculate the height of the left and right subtree.
int l = height(root->left);
int r = height(root->right);

//if difference between height of left and right subtree is less than equal to 1 and left and right subtree is also height balanced then return true
if( abs(l - r) <= 1 && is_balanced(root->left)==true && is_balanced(root->right)==true)
{
return true;
}

//else return false
return 0;
}

//function to count and return the number of nodes int he given BST with root given
int count_nodes(node* root)
{
//if tree is empty return 0.
if (root==NULL)
{
return 0;
}
//otherwise return the count of nodes in left and right subtree +1 (for the current node)
return 1 + count_nodes(root->left) + count_nodes(root->right);
}

//function to check if the given BST is complete or not i.e, tree is full except the last level and all the leaf in last level are on left as possible.
bool is_complete ( node* root, int index,int total_nodes)
{
//if tree is empty then return true
if (root == NULL)
{
return true;
}

//if index of the current node is more than equal to the count of nodes then tree is not complete.
if (index >= total_nodes)
{
return false;
}

//if true for this node then check for left and right subtree and return the result.
return (is_complete(root->left, 2*index+1, total_nodes) && is_complete(root->right, 2*index+2, total_nodes));
}
//function to convert a string of integer to integer data type
int str_to_int(string &str)
{
//answer initialized to 0.
int ans=0;
//traverse string and add to answer considering number in base 10.
for(int i=0;i<str.size();i++)
{
ans=ans*10+(str[i]-'0');
}
//return answer.
return ans;
}
//to get minimum branch height starting from root to some leaf node.
int get_min(node*root)
{
//if empty tree then return 0.
if(root==NULL)
{
return 0;
}
//otherwise get minimum branch height of left and right subtree and add 1 for the current node.
return 1+min(get_min(root->left), get_min(root->right));
}
//driver function
int main()
{
//ifstream object to read a file containing dataset
ifstream Fp;
Fp.open("test.txt");
//string variable to read integer in each line
string str;
//root of the BST formed initialized to NULL i.e, initially empty.
node *root = NULL;

//read each line from file until EOF
while(getline(Fp, str))
{
//if root is NULL then this integer will be root node.
if(root==NULL)
{
//insert node with this value and make this node as root.
root=insert(root, str_to_int(str));
}
//otherwise insert it into BST with root.
else
{
insert(root, str_to_int(str));
}

}
//close file.
Fp.close();

//printing the values
cout<<"The smallest branch height is : "<<get_min(root)<<endl;
cout<<"The highest branch height is : "<<height(root)<<endl;

//call for counting node in the tree.
int counter=count_nodes(root);
cout<<"Number of nodes in the tree: "<<count_nodes(root)<<endl;

//call to check balancing of the tree
bool flag=is_balanced(root);
if(flag==true)
{
cout<<"Tree is balanced"<<endl;
}
else
{
cout<<"Tree is not balanced"<<endl;
}

   //check if tree is complete or not.
   flag=is_complete(root, 0, counter);
   if(flag==true)
{
cout<<"Tree is complete"<<endl;
}
else
{
cout<<"Tree is not complete"<<endl;
}

//return from main
return 0;
}

  • INPUT:15
    8
    31
    42
    60
    78
    77
    75
    80
    88
    89
    99
  • OUTPUT:The smallest branch height is : 2
    The highest branch height is : 9
    Number of nodes in the tree: 12
    Tree is not balanced
    Tree is not complete
  • The BST looks like:

15 Root ग

  • For better clarity as the code is a bit lengthy , the picture of the code and input/ouput is given below.

//include all necessary headers. #include <iostream> #include <fstream> using namespace std; // structure of node of BST (bin

node->left = insert (node->left, val); else if (val > node->data) node->right = insert (node->right, val); L //return the nod

return true; //else return false return 0; 7/function to count and return the number of nodes int he given BST with root give

мно return (is_complete (root->left, 2*index+l, total_nodes) && is complete (root->right, 2*index+2, total_nodes)); L} //func

//read each line from file until EOF while (getline (Ep, str)) //if root is NULL then this integer will be root node. if (roo

cout<<Tree is not balanced<<endl; // check if tree is complete or not. flag=is_complete (root, 0, counter); if (flag==true)

Input/Output:

-ox test - Notepad File Edit Format 15 View Help (31

The smallest branch height is : 2 The highest branch height is : 9 Number of nodes in the tree: 12 Tree is not balanced Tree

So if you have any doubt regarding this code and it's explanation please feel free to ask in the comment section and if it is helpful then please give an up vote to this solution, THANK YOU.

Add a comment
Know the answer?
Add Answer to:
Construct a Binary Search Tree (BST) program in C++. The program is required to: 1) load...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • help 2. Do the following problems: Create a binary search tree (BST), with the following words...

    help 2. Do the following problems: Create a binary search tree (BST), with the following words inserted: Int, Char, Return, Break, Float, While, Short, Sort, Double, For, Continue. a. b. Insert the following words into the BST built in (a): Tree, Table, Binary, Network, Visit, Seekk, Traversal c. Where is the minimum key value in a BST? (Give a concrete example) d. Where is the maximum key value in a BST? (Give a concrete example) e. How many comparisons are...

  • Write a program in C fro Binary Search tree using following functions 1. Insertion operation using...

    Write a program in C fro Binary Search tree using following functions 1. Insertion operation using recursion 2. Deletion operation 3. Minimum/Maximum of a BST 6. Reorganize the tree so that the tree height is minimum 7. Print all the nodes from the node to the path to the root 8. Find the lowest common shared node between two given nodes

  • Programming in C++ Implement a BST (Binary Search Tree) and test your program. (Linked List based.)...

    Programming in C++ Implement a BST (Binary Search Tree) and test your program. (Linked List based.) You should test at least the three major functions. (Insert, Retrieve, and Delete).

  • 1. Construct a Binary Search Tree 50 Write code to implement a BST. Implement an add) method and ...

    C++ program 1. Construct a Binary Search Tree 50 Write code to implement a BST. Implement an add) method and a remove) method. Use the following input to construct a BST: 50,20,75,98,80,31,150, 39, 23,11,77 20 75 31 98 0 (150 Hint on removing If the node to be removed is: a leaf node a node with a left child only a node with a right child only a node with both children Then take this action replace with null replace...

  • Q1: How many levels your binary search tree has (including level 0)? Is the binary search...

    Q1: How many levels your binary search tree has (including level 0)? Is the binary search tree you created height balanced? 2.1 Click the animations “Binary Search Tree”. Click “Insert” button to insert the following elements in the sequence, “50, 20, 30, 70, 90, 80, 40, 10, 5, 60, 85, 95”. http://algoanim.ide.sk/index.php?page=showanim&id=44 Q2: What is the insertion process of the binary search tree? The new identical element is inserted as left or right child of the existing same value? 2.3...

  • Q1: How many levels your binary search tree has (including level 0)? Is the binary search tree you created height balanc...

    Q1: How many levels your binary search tree has (including level 0)? Is the binary search tree you created height balanced? 2.1 Click the animations “Binary Search Tree”. Click “Insert” button to insert the following elements in the sequence, “50, 20, 30, 70, 90, 80, 40, 10, 5, 60, 85, 95”. http://algoanim.ide.sk/index.php?page=showanim&id=44 Q2: What is the insertion process of the binary search tree? The new identical element is inserted as left or right child of the existing same value? 2.3...

  • Need this in C++ Goals: Your task is to implement a binary search tree of linked...

    Need this in C++ Goals: Your task is to implement a binary search tree of linked lists of movies. Tree nodes will contain a letter of the alphabet and a linked list. The linked list will be an alphabetically sorted list of movies which start with that letter. MovieTree() ➔ Constructor: Initialize any member variables of the class to default ~MovieTree() ➔ Destructor: Free all memory that was allocated void printMovieInventory() ➔ Print every movie in the data structure in...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • C++ Binary Search Tree question. I heed help with the level 2 question please, as level...

    C++ Binary Search Tree question. I heed help with the level 2 question please, as level 1 is already completed. I will rate the answer a 100% thumbs up. I really appreciate the help!. Thank you! searching.cpp #include <getopt.h> #include <iostream> #include <sstream> #include <stdlib.h> #include <unistd.h> using namespace std; // global variable for tree operations // use to control tree maintenance operations enum Mode { simple, randomised, avl } mode; // tree type // returns size of tree //...

  • C++ Binary Search Tree question. I heed help with the level 2 question please, as level...

    C++ Binary Search Tree question. I heed help with the level 2 question please, as level 1 is already completed. I will rate the answer a 100% thumbs up. I really appreciate the help!. Thank you! searching.cpp #include <getopt.h> #include <iostream> #include <sstream> #include <stdlib.h> #include <unistd.h> using namespace std; // global variable for tree operations // use to control tree maintenance operations enum Mode { simple, randomised, avl } mode; // tree type // returns size of tree //...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT