Question

In C++ I need the printRange function, and the main.cpp program. Thanks. (Binary search tree) Write...

In C++ I need the printRange function, and the main.cpp program. Thanks.

(Binary search tree) Write a function printRange that takes as input a binary search tree t and two keys, k1 and k2, which are ordered so that k1 < k2, and print all elements x in the tree such that k1 <= x <= k2.

You can add this function in BinarySearchTree.h (click the link) that we used in the lecture and lab 7.

public:

void printRange(int k1, int k2)

{ printRange(root,k1, k2);

}

private:

void printRange(BinaryNode* t, int k1, int k2)

{

// add your code

}

Here are the sample runs:

insert the values (stop when entering 0): 10 5 20 3 22 6 18 7 9 13 15 4 2 1 19 30 8 0

enter the range of values: 8 18

print the values: 8, 9, 10, 13, 15, 18,

Here is BinarySearchTree.h

#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H

#include <cassert>
#include <iostream>
using namespace std;      

template <typename C>
class BinarySearchTree
{
  public:
    BinarySearchTree( ) : root{ nullptr }
    {
    }

    ~BinarySearchTree( ) 
    { 
        makeEmpty();
    }   

    bool isEmpty( ) const
    {
        return root == nullptr;
    } 

    const C & findMin( ) const
    {
      assert(!isEmpty());
      return findMin( root )->element;
    }

    const C & findMax( ) const
    {
      assert(!isEmpty());
      return findMax( root )->element;
    }
    
    bool contains( const C & x ) const
    {
        return contains( x, root );
    }  

    void printTree( ) const
    {
        if( isEmpty( ) )
            cout << "Empty tree" << endl;
        else
            printTree( root );
    }

    void makeEmpty( )
    {
        makeEmpty( root );
    }
    
    void insert( const C & x )
    {
        insert( x, root );
    }     

    void remove( const C & x )
    {
        remove( x, root );
    }

  private:
    
    struct BinaryNode
    {
        C element;
        BinaryNode* left;
        BinaryNode* right;

        BinaryNode( const C & theElement, BinaryNode* lt, BinaryNode* rt )
          : element{ theElement }, left{ lt }, right{ rt } 
        { }
    };

    BinaryNode* root;
    
    // Internal method to find the smallest item in a subtree t.
    // Return node containing the smallest item.    
    BinaryNode* findMin( BinaryNode* t ) const
    {
        if( t == nullptr )
            return nullptr;
        if( t->left == nullptr )
            return t;
        return findMin( t->left );
    }
    
    // Internal method to find the largest item in a subtree t.
    // Return node containing the largest item.
    BinaryNode* findMax( BinaryNode* t ) const
    {
        if( t != nullptr )
            while( t->right != nullptr )
                t = t->right;
        return t;
    }

    // Internal method to test if an item is in a subtree.
    // x is item to search for.
    // t is the node that roots the subtree.    
    bool contains( const C & x, BinaryNode* t ) const
    {
        if( t == nullptr )
            return false;
        else if( x < t->element )
            return contains( x, t->left );
        else if( t->element < x )
            return contains( x, t->right );
        else
            return true;    // Match
    }

    void printTree( BinaryNode* t) const
    {
        if( t != nullptr )
        {
            printTree( t->left);
            cout << t->element << " - ";
            printTree( t->right);
        }
    }
    
    void makeEmpty( BinaryNode* & t )
    {
        if( t != nullptr )
        {
            makeEmpty( t->left );
            makeEmpty( t->right );
            delete t;
        }
        t = nullptr;
    }
    
    // Internal method to insert into a subtree.
    // x is the item to insert.
    // t is the node that roots the subtree.
    // Set the new root of the subtree.    
    void insert( const C & x, BinaryNode* & t )
    {
        if( t == nullptr )
            t = new BinaryNode{ x, nullptr, nullptr };
        else if( x < t->element )
            insert( x, t->left );
        else if( t->element < x )
            insert( x, t->right );
        else
            ;  // Duplicate; do nothing
    }
    
    // Internal method to remove from a subtree.
    // x is the item to remove.
    // t is the node that roots the subtree.
    // Set the new root of the subtree.    
    void remove( const C & x, BinaryNode* & t )
    {
        if( t == nullptr )
            return;   // Item not found; do nothing
        if( x < t->element )
            remove( x, t->left );
        else if( t->element < x )
            remove( x, t->right );
        else if( t->left != nullptr && t->right != nullptr ) // Two children
        {
            t->element = findMin( t->right )->element;
            remove( t->element, t->right );
        }
        else
        {
            BinaryNode* oldNode = t;
            if ( t->left == nullptr )
                t = t->right;
            else
                t = t->left;
            delete oldNode;
        }
    }

};
#endif
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//C ++ program

public:

void printRange(int k1, int k2)

{ printRange(root,k1, k2);

}

private:

void printRange(BinaryNode* root, int k1, int k2)

{
   /* base case */
if ( root == NULL )
return;
  
/* Since the desired o/p is sorted, recurse for left subtree first
If root->data is greater than k1, then only we can get o/p keys
in left subtree */
if ( k1 < root->data )
printRange(root->left, k1, k2);
  
/* if root's data lies in range, then prints root's data */
if ( k1 <= root->data && k2 >= root->data )
cout<< root->data ;
  
/* If root->data is smaller than k2, then only we can get o/p keys
in right subtree */
if ( k2 > root->data )
printRange(root->right, k1, k2);


}

Add a comment
Know the answer?
Add Answer to:
In C++ I need the printRange function, and the main.cpp program. Thanks. (Binary search tree) Write...
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
  • Take the following code for a binary source tree and make it include the following operations....

    Take the following code for a binary source tree and make it include the following operations. bool replace(const Comparable & item, const Comparable & replacementItem); int getNumberOfNodes() const; (a) The replace method searches for the node that contains item in a binary search tree, if it is found, it replaces item with replacementItem. The binary tree should remain as a binary search tree after the replacement is done. Add the replace operation to the BinarySearchTree class. Test your replace using...

  • After the header, each line of the database file rebase210.txt contains the name of a restriction...

    After the header, each line of the database file rebase210.txt contains the name of a restriction enzyme and possible DNA sites the enzyme may cut (cut location is indicated by a ‘) in the following format: enzyme_acronym/recognition_sequence/…/recognition_sequence// For instance the first few lines of rebase210.txt are: AanI/TTA'TAA// AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG// AasI/GACNNNN'NNGTC// AatII/GACGT'C// AbsI/CC'TCGAGG// AccI/GT'MKAC// AccII/CG'CG// AccIII/T'CCGGA// Acc16I/TGC'GCA// Acc36I/ACCTGCNNNN'NNNN/'NNNNNNNNGCAGGT// … That means that each line contains one enzyme acronym associated with one or more recognition sequences. For example on line 2:The enzyme acronym...

  • Hi there, I am working on a binary search tree code in c++. The program must...

    Hi there, I am working on a binary search tree code in c++. The program must store and update students' academic records, each node includes the student name, credits attempted, credits earned and GPA. I have made some progress with the code and written most of the functions in the .cpp file (already did the .h file) but i am struggling with what to put in the main and how to put an update part in the insert function. I...

  • Hello. I have written the following function to remove a value from a Binary Search Tree using re...

    Hello. I have written the following function to remove a value from a Binary Search Tree using resources my professors gave and stuff I found online. The problem is I don't know how it works and I need to know how it works to finish the rest of the project. public boolean remove(T value){ if(value == null) return false; class RemoveBSTObj{ private boolean found = false; private Node removeBST(Node root, T value){ if(root == null) return root; //IF there is...

  • Question - modify the code below so that for a node, the value of every node...

    Question - modify the code below so that for a node, the value of every node of its right subtree is less the node, and the value of each node of its left subtree is greater than the node. - create such a binary tree in the Main method, and call the following method:  InOrder(Node theRoot),  PreOrder(Node theRoot),  PostOrder(Node theRoot),  FindMin(),  FindMax(),  Find(int key) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;...

  • I need to do a tree sort method but the treesortMethod is not working /****Binarytree class****\...

    I need to do a tree sort method but the treesortMethod is not working /****Binarytree class****\ package Tree; public class BinaryTree { private TreeNode root; // head of the list    //constructor - create an empty binary tree public BinaryTree() { root = null;    }    //isEmpty() - return true if tree is empty, false otherwise public boolean isEmpty() { return (root == null); }    //deleteTree() - remove all items from tree public void deleteList() { root =...

  • C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree...

    C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree methods (bst.cpp) for the binary search tree provided in the header file. Test your implementation with the included test. bst.h bst_test.cpp Note: Your implementation must correspond to declarations in the header file, and pass the test. Do not modify these two. I will compile your code against these. If the compilation fails, you will get down vote. bst.h #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include <string>...

  • Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary...

    Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Add this function to the class binaryTreeType and create a program to test this function. #include <iostream> using namespace std; //Definition of the Node template <class elemType> struct nodeType { elemType info; nodeType<elemType> *lLink; nodeType<elemType> *rLink; }; //Definition of the class template <class elemType> class binaryTreeType { public: //Overload the assignment operator. const binaryTreeType<elemType>& operator=(const binaryTreeType<elemType>&) { if (this != &otherTree) //avoid self-copy...

  • Write a C++ program to validate computer user-ids and passwords. A list of valid ids and...

    Write a C++ program to validate computer user-ids and passwords. A list of valid ids and passwords (unsorted) is read from a file and stored in a Binary Search Tree (BST) of UserInfo objects. When user-ids and passwords are entered during execution, this BST is searched to determine whether they are legal. Input (file): UserInfo records for valid users Input (keyboard): Ids and passwords of users logging in Output (screen): Messages indicating whether user-ids and passwords are valid, as well...

  • 1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the...

    1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the number of leaf nodes in the tree. 2) Extend the Binary Search Tree ADT to include a public method singleParent-Count that returns the number of nodes in the tree that have only one child. 3) The Binary search tree ADT is extended to include a boolean method similarTrees that receives references to two binary trees and determines whether the shapes of the trees are...

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