Question

In: Computer Science

Create a (partial) BST class and a driver program to test it. The tree node will...

Create a (partial) BST class and a driver program to test it. The tree node will store integers as the data/key field (single field). Note that you will need to guarantee there are no duplicates in your insert function (the tree should refuse to insert a duplicate key). Call your files “tree.h”, “tree.cpp” and “main.cpp”. In addition, draw a picture of your tree (see note about random values below)

Public methods to include:

  • Constructor
  • Copy Constructor
  • Overloaded Assignment Operator
  • Destructor
  • Insert value (do not add duplicate values)
  • Find key – returns bool indicating if value is present in tree
  • Print ancestors – prints a list of all values on the path to the given value
  • Find height – returns integer
  • Post-Order Traversal done recursively (print key values to screen)
  • In-Order Traversal done iteratively (print key values to screen) (use STL Stack for this – see instructions on Canvas course site)
  • Count leaves – returns number of leaves in tree Count full nodes – returns number of full nodes (nodes with two children) in tree

There will be additional private helper methods needed. The only methods that may print to the screen are the two traversals and the print ancestors.

Your driver should insert a minimum of 25 random* values to the tree. Test all the public methods of your class in the driver, printing the results to the screen. The user interface should clearly explain what is being tested and what results are expected.

*Random doesn’t mean you need to use the random number generator, though you are welcome to do so. But it does mean you do not want to insert values 1 thru 20 (in that order) into your tree (why not?). Consequently, you should decide on your values in advance and store them (in an array??) to insert. Include at least one duplicate value to properly test the insert.

Solutions

Expert Solution

1. Insert node and print Inorder Traversal :

#include <iostream>

using namespace std;

class BST

{

    int data;

    BST *left, *right;

    public:

    BST();

    BST(int);

     

    // Insert function.

    BST* Insert(BST *, int);

     

    // Inorder traversal.

    void Inorder(BST *);

};

BST :: BST() : data(0), left(NULL), right(NULL){}

BST :: BST(int value)

{

    data = value;

    left = right = NULL;

}

BST* BST :: Insert(BST *root, int value)

{

    if(!root)

    {

     // if root NULL then insert node.

        return new BST(value);

    }

    // Insert data.

    if(value > root->data)

    {

        root->right = Insert(root->right, value);

    }

    else

    {

root->left = Insert(root->left, value);

    }

    return root;

}

void BST :: Inorder(BST *root)

{

    if(!root)

    {

        return;

    }

    Inorder(root->left);

    cout << root->data << endl;

    Inorder(root->right);

}

int main()

{

    BST b, *root = NULL;

    root = b.Insert(root, 50);

    b.Insert(root, 30);

    b.Insert(root, 20);

    b.Insert(root, 40);

    b.Insert(root, 70);

    b.Insert(root, 60);

    b.Insert(root, 80);

    b.Inorder(root);

    return 0;

}

2. Find key:

#include <iostream>

using namespace std;

// Binary tree node

struct Node {

    int data;

    struct Node *left, *right;

    Node(int data)

    {

        this->data = data;

        left = right = NULL;

    }

};

bool ifNodeExists(struct Node* node, int key)

{

    if (node == NULL)

        return false;

    if (node->data == key)

        return true;

    /* then recur on left sutree */

    bool res1 = ifNodeExists(node->left, key);

    // node found

    if(res1) return true;

   //node not prsent at left side

    bool res2 = ifNodeExists(node->right, key);

    return res2;

}

// Driver Code

int main()

{

    struct Node* root = new Node(0);

    root->left = new Node(1);

    root->left->left = new Node(3);

    root->left->left->left = new Node(17);

    root->left->right = new Node(4);

    root->left->right->left = new Node(8);

    root->left->right->right = new Node(90);

    root->right = new Node(2);

    root->right->left = new Node(5);

    root->right->right = new Node(6);

    int key = 4;

    if (ifNodeExists(root, key))

        cout << "YES";

    else

        cout << "NO";

    return 0;

}

3. count no. of leaf node in tree:

#include <bits/stdc++.h>

using namespace std;

struct node

{

    int data;

    struct node* left;

    struct node* right;

};

unsigned int getLeafCount(struct node* node)

{

    if(node == NULL)     

        return 0;

    if(node->left == NULL && node->right == NULL)

        return 1;         

    else

        return getLeafCount(node->left)+

            getLeafCount(node->right);

}

struct node* newNode(int data)

{

    struct node* node = (struct node*)

                    malloc(sizeof(struct node));

    node->data = data;

    node->left = NULL;

    node->right = NULL;

     

return(node);

}

int main()

{

    /*create a tree*/

    struct node *root = newNode(1);

    root->left = newNode(12);

    root->right = newNode(13);

    root->left->left = newNode(40);

    root->left->right = newNode(75);

     

cout << "No. of leaf node: "<<

                getLeafCount(root) << endl;

return 0;

}

4. To calculate height of tree:

#include <bits/stdc++.h>

using namespace std;

class node

{

    public:

    int data;

    node* left;

    node* right;

};

int maxDepth(node* node)

{

    if (node == NULL)

        return 0;

    else

    {

        int lDepth = maxDepth(node->left);

        int rDepth = maxDepth(node->right);        

        if (lDepth > rDepth)

            return(lDepth + 1);

        else return(rDepth + 1);

    }

}

node* newNode(int data)

{

    node* Node = new node();

    Node->data = data;

    Node->left = NULL;

    Node->right = NULL;

     

    return(Node);

}   

int main()

{

    node *root = newNode(1);

root->left = newNode(2);

    root->right = newNode(3);

    root->left->left = newNode(4);

    root->left->right = newNode(5);

     

    cout << "Height of tree is " << maxDepth(root);

    return 0;

}


Related Solutions

In this class add Comparable interface. In the driver program create a few objects and In...
In this class add Comparable interface. In the driver program create a few objects and In the driver program create a few objects and compare them . then create a list of those objects and sort them .A Quadratic is bigger than another Quadratic if it opens faster package pack2; /** * This is a program for defining a quadratic equation * @author sonik */ public class Quadratic { public int coeffX2 = 0; public int coeffX = 0; public...
java code Add the following methods to the LinkedQueue class, and create a test driver for...
java code Add the following methods to the LinkedQueue class, and create a test driver for each to show that they work correctly. In order to practice your linked list cod- ing skills, code each of these methods by accessing the internal variables of the LinkedQueue, not by calling the previously de?ined public methods of the class. String toString() creates and returns a string that correctly represents the current queue. Such a method could prove useful for testing and debugging...
28. Add the following methods to the ArrayBoundedStack class, and create a test driver for each...
28. Add the following methods to the ArrayBoundedStack class, and create a test driver for each to show that they work correctly. In order to practice your array related coding skills, code each of these methods by accessing the internal variables of the ArrayBoundedStack, not by calling the previously defined public methods of the class. a. String toString()—creates and returns a string that correctly represents the current stack. Such a method could prove useful for testing and debugging the class...
Add the following method below to the CardDeck class, and create a test driver to show...
Add the following method below to the CardDeck class, and create a test driver to show that they work correctly. int cardsRemaining() //returns a count of the number of undealt cards remaining in the deck. Complete in Java programming language. // Models a deck of cards. Includes shuffling and dealing. //---------------------------------------------------------------------- package Homework4; import java.util.Random; import java.util.Iterator; import javax.swing.ImageIcon; public class CardDeck { public static final int NUMCARDS = 52; protected ABList<Card> deck; protected Iterator<Card> deal; public CardDeck() { deck...
I was trying to implement a simple binary search tree using this given class of bst...
I was trying to implement a simple binary search tree using this given class of bst in c++ public: BST(); ~BST(); void insertKey(int newKey); bool hasKey(int searchKey); std::vector<int> inOrder(); int getHeight(); however; i am still required to use another class for the nodes as a pointer and i need to manage memory leak. in main we should ask for the numbers we need to insert in the binary search tree and also let the user end it with a letter...
JAVA (Tree height) Define a new class named BSTWithHeight that extends BST with the following method:...
JAVA (Tree height) Define a new class named BSTWithHeight that extends BST with the following method: /** Return the height of this binary tree */ public int height() Class Name: Exercise25_01
Write a program to do the following. • Input an integer n. • Create a BST...
Write a program to do the following. • Input an integer n. • Create a BST S inserting the keys 1, 2, . . . , n in that order, which will result in a completely-skewed tree. • Measure the time to search for n + 1 in S. • Display the time taken for search. /** * Exception class for access in empty containers * such as stacks, queues, and priority queues. * @author Mark Allen Weiss */ public...
Write a program to do the following. • Input an integer n. • Create a BST...
Write a program to do the following. • Input an integer n. • Create a BST B containing the same items, but inserting them in an order that will yield the tree balanced. The following algorithm, known as pre-order traversal, gives you a strategy to produce that sequence. seq(low, high, T){    if (low <= high){        mid = (low+high)/2        T.insert(mid)        seq(low, mid-1, T)        seq(mid+1, high, T)    } } • Measure the...
Create a random binary tree and verify BST property and AVL balance condition. Do not hard...
Create a random binary tree and verify BST property and AVL balance condition. Do not hard code the tree inside the code. Java or C++ are the options.
Implement a function to find a node in a binary search tree. Using the following class...
Implement a function to find a node in a binary search tree. Using the following class and function definition. If a node with a matching value is found, return a pointer to it. If no match is found, return nullptr. #include <iostream> class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode *find(int item) { //implement code here return nullptr; } int main() {    root = new...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT