473,804 Members | 3,138 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Binary Search Tree Input Problem

I have everything pretty much done but I need to fix something in my
coding. I want to be able to enter strings such as "love", "hate",
"the", etc. but am unable to figure how to do this. I have put my .cpp
and my .h code below. Please help and thank you very much.

// include files
#ifndef BINTREE_H
#define BINTREE_H
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

// data types
typedef char DataType;

// TreeNode struct (includes constructor)
struct TreeNode
{
DataType data;
TreeNode *left, *right;

// constructor
TreeNode( DataType d = 0, TreeNode * l = NULL, TreeNode * r = NULL
) :
data( d ), left( l ), right( r ) { }
};

// ------------------------------------------------------------------
// BinarySearchTre e class
// ------------------------------------------------------------------
class BinarySearchTre e
{
private:

// private data members
TreeNode* root;
int level; // class variable to help format printing

// private member functions
void FreeTree( TreeNode* & );
TreeNode* Search( DataType, TreeNode* ) const;
void Insert( DataType, TreeNode* & );
void Delete( DataType, TreeNode* & );
void Print( TreeNode* );
void PrintInorder( TreeNode* ) const;

public:

// public member functions

// constructor
BinarySearchTre e( ) : root( NULL ) { }

// call recursive insert method
void Insert( DataType item ) { Insert( item, root ); }

// print the tree on its side, showing structure
void Print( ) { level = 0; Print( root ); }

// call recursive print method
void PrintInorder( ) const { PrintInorder( root ); }
};

#endif
// include files
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include "bst.h"
using namespace std;

// Recursively insert an item in the tree, if not already present.
// Note that we pass root by reference.
void BinarySearchTre e::Insert( DataType item, TreeNode* & root )
{
if ( root == NULL ) // hit NULL pointer, insert here
{
root = new TreeNode( item );
if ( root == NULL )
cerr << "Error: cannot allocate memory for TreeNode in
Insert()!\n";
}

else if ( item < root->data ) // insert in left subtree
Insert( item, root->left );

else if ( item > root->data ) // insert in right subtree
Insert( item, root->right );
}

// Recursive inorder tree traversal (called by Print function).
// Print the tree on its side, rotated counterclockwis e to show
structure.
void BinarySearchTre e::Print( TreeNode* nodeptr )
{
int i;

if ( nodeptr )
{
level++;

for ( i = 0; i < level; i++ )
cout << setw( 3 ) << ' ';
Print( nodeptr->right );

cout << '\r';
for ( i = 0; i < level - 1; i++ )
cout << setw( 3 ) << ' ';
cout << nodeptr->data << endl;

for ( i = 0; i < level; i++ )
cout << setw( 3 ) << ' ';
Print( nodeptr->left );

level--;
}
}

// Recursive tree traversals (called by Print routines).
// Print tree items inorder.
void BinarySearchTre e::PrintInorder ( TreeNode* nodeptr ) const
{
if ( nodeptr != NULL )
{
PrintInorder( nodeptr->left ); // print left subtree
cout << nodeptr->data << ' '; // print root
PrintInorder( nodeptr->right ); // print right subtree
}
}

// Program to test BinarySearchTre e class: main() function
int main( )
{
BinarySearchTre e tree;
DataType item;
int n = 20;
char answer;
cout<<"Would you like to enter the numbers or have the system
generate";
cout<<"them randomly. R for random and U for user input."<<endl;
cin>>answer;
if(answer == 'R' || answer =='r')
{
// generate a BST of random int values
srand( time( NULL ) ); // init random number generator
cout << "Inserting " << n << " items in the BST:";
for ( int i = 0; i < n; i++ )
{
item = rand() % n; // generate a random int between 0 and n-1
tree.Insert( item ); // insert it in the BST
if ( i % 10 == 0 ) cout << endl;
cout << setw( 7 ) << item;
}
}
else if(answer == 'U' || answer =='u')
{
cout<<"Enter data with spaces in between. # terminates the
input"<<endl;
do
{
cin>>item;
if(item != '#')
tree.Insert(ite m);
} while(item != '#');
}
else
cout<<"Wrong input."<<endl;

// print the tree
cout <<endl;
cout <<"Duplicates will not be shown"<<endl;
cout << "\n\nBST contents:\n";
tree.PrintInord er( );

cout << "\n\nBST structure:\n";
tree.Print( );
cout<<endl;

cout<<"Goodbye" <<endl;

return EXIT_SUCCESS;
}
again thanks for the help
Jul 22 '05 #1
4 2832
On 26 Jul 2004 18:08:19 -0700, Henry Jordon <bu*******@hotm ail.com> wrote:
I have everything pretty much done but I need to fix something in my
coding. I want to be able to enter strings such as "love", "hate",
"the", etc. but am unable to figure how to do this. I have put my .cpp
and my .h code below. Please help and thank you very much.


It seems very unlikely that you could write all that code and yet not do
this seemingly simple task. What exactly is confusing you? What did you
attempt?

Here's a start

Add this.

#include <string>

Replace this

typedef char DataType;

with this.

typedef std::string DataType;

I think you'll have one or two more changes to make, but if you have any
understanding at all of the code you are working with I don't think you'll
find it too difficult.

john
Jul 22 '05 #2
In message <opsbr7wzkp2123 31@andronicus>, John Harrison
<jo************ *@hotmail.com> writes
On 26 Jul 2004 18:08:19 -0700, Henry Jordon <bu*******@hotm ail.com> wrote:
I have everything pretty much done but I need to fix something in my
coding. I want to be able to enter strings such as "love", "hate",
"the", etc. but am unable to figure how to do this. I have put my .cpp
and my .h code below. Please help and thank you very much.


It seems very unlikely that you could write all that code and yet not
do this seemingly simple task.


A possible explanation of your confusion may be found here:

http://www.hpcnet.org/upload/directo...31027093651.cc

;-)

--
Richard Herring
Jul 22 '05 #3

On 26 Jul 2004 18:08:19 -0700, bu*******@hotma il.com (Henry Jordon)
wrote:
I have everything pretty much done but I need to fix something in my
coding. I want to be able to enter strings such as "love", "hate",
"the", etc. but am unable to figure how to do this. I have put my .cpp
and my .h code below. Please help and thank you very much.

// include files
#ifndef BINTREE_H
#define BINTREE_H
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

// data types
typedef char DataType;

// TreeNode struct (includes constructor)
struct TreeNode
{
DataType data;
TreeNode *left, *right;

// constructor
TreeNode( DataType d = 0, TreeNode * l = NULL, TreeNode * r = NULL You have a semi-colon here. It should be a colon or whatever you call
it, I always get them mixed up but you know what I mean, you have the
wrong line terminator right below my comments.
***********) : right here. should be ); *********** data( d ), left( l ), right( r ) { }
};

// ------------------------------------------------------------------
// BinarySearchTre e class
// ------------------------------------------------------------------
class BinarySearchTre e
{
private:

// private data members
TreeNode* root;
int level; // class variable to help format printing

// private member functions
void FreeTree( TreeNode* & );
TreeNode* Search( DataType, TreeNode* ) const;
void Insert( DataType, TreeNode* & );
void Delete( DataType, TreeNode* & );
void Print( TreeNode* );
void PrintInorder( TreeNode* ) const;

public:

// public member functions

// constructor
BinarySearchTre e( ) : root( NULL ) { }

// call recursive insert method
void Insert( DataType item ) { Insert( item, root ); }

// print the tree on its side, showing structure
void Print( ) { level = 0; Print( root ); }

// call recursive print method
void PrintInorder( ) const { PrintInorder( root ); }
};

#endif
// include files
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include "bst.h"
using namespace std;

// Recursively insert an item in the tree, if not already present.
// Note that we pass root by reference.
void BinarySearchTre e::Insert( DataType item, TreeNode* & root )
{
if ( root == NULL ) // hit NULL pointer, insert here
{
root = new TreeNode( item );
if ( root == NULL )
cerr << "Error: cannot allocate memory for TreeNode in
Insert()!\n" ;
}

else if ( item < root->data ) // insert in left subtree
Insert( item, root->left );

else if ( item > root->data ) // insert in right subtree
Insert( item, root->right );
}

// Recursive inorder tree traversal (called by Print function).
// Print the tree on its side, rotated counterclockwis e to show
structure.
void BinarySearchTre e::Print( TreeNode* nodeptr )
{
int i;

if ( nodeptr )
{
level++;

for ( i = 0; i < level; i++ )
cout << setw( 3 ) << ' ';
Print( nodeptr->right );

cout << '\r';
for ( i = 0; i < level - 1; i++ )
cout << setw( 3 ) << ' ';
cout << nodeptr->data << endl;

for ( i = 0; i < level; i++ )
cout << setw( 3 ) << ' ';
Print( nodeptr->left );

level--;
}
}

// Recursive tree traversals (called by Print routines).
// Print tree items inorder.
void BinarySearchTre e::PrintInorder ( TreeNode* nodeptr ) const
{
if ( nodeptr != NULL )
{
PrintInorder( nodeptr->left ); // print left subtree
cout << nodeptr->data << ' '; // print root
PrintInorder( nodeptr->right ); // print right subtree
}
}

// Program to test BinarySearchTre e class: main() function
int main( )
{
BinarySearchTre e tree;
DataType item;
int n = 20;
char answer;
cout<<"Would you like to enter the numbers or have the system
generate";
cout<<"them randomly. R for random and U for user input."<<endl;
cin>>answer;
if(answer == 'R' || answer =='r')
{
// generate a BST of random int values
srand( time( NULL ) ); // init random number generator
cout << "Inserting " << n << " items in the BST:";
for ( int i = 0; i < n; i++ )
{
item = rand() % n; // generate a random int between 0 and n-1
tree.Insert( item ); // insert it in the BST
if ( i % 10 == 0 ) cout << endl;
cout << setw( 7 ) << item;
}
}
else if(answer == 'U' || answer =='u')
{
cout<<"Enter data with spaces in between. # terminates the
input"<<endl ;
do
{
cin>>item;
if(item != '#')
tree.Insert(ite m);
} while(item != '#');
}
else
cout<<"Wrong input."<<endl;

// print the tree
cout <<endl;
cout <<"Duplicates will not be shown"<<endl;
cout << "\n\nBST contents:\n";
tree.PrintInord er( );

cout << "\n\nBST structure:\n";
tree.Print( );
cout<<endl;

cout<<"Goodbye" <<endl;

return EXIT_SUCCESS;
}
again thanks for the help


Jul 22 '05 #4
In message <aj************ *************** *****@4ax.com>, Mark R Rivet
<ma********@ver izon.net> writes

On 26 Jul 2004 18:08:19 -0700, bu*******@hotma il.com (Henry Jordon)
wrote:
I have everything pretty much done but I need to fix something in my
coding. I want to be able to enter strings such as "love", "hate",
"the", etc. but am unable to figure how to do this. I have put my .cpp
and my .h code below. Please help and thank you very much.

// include files
#ifndef BINTREE_H
#define BINTREE_H
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

// data types
typedef char DataType;

// TreeNode struct (includes constructor)
struct TreeNode
{
DataType data;
TreeNode *left, *right;

// constructor
TreeNode( DataType d = 0, TreeNode * l = NULL, TreeNode * r = NULL

You have a semi-colon here. It should be a colon or whatever you call
it, I always get them mixed up but you know what I mean, you have the
wrong line terminator right below my comments.
***********
) : right here. should be );

***********
data( d ), left( l ), right( r ) { }


Wrong. That's a constructor definition and the colon introduces an
initializer list.

John M Weiss's code
(http://www.hpcnet.org/upload/directo...31027093651.cc)
is fine, even if Mr Jordan did fail to acknowledge his authorship.
Somehow I don't think he's going to get full marks for this piece of
homework.

--
Richard Herring
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2856
by: tsunami | last post by:
hi all; I have an array and want to insert all the elements from this array to a binary search tree.That array is an object of the class of a stringtype which includes overloaded "< > = ==" functions and every other thing it needs. void InsertElementFromArray(StringType Array,int first element,int last element);
4
9023
by: Tarique Jawed | last post by:
Alright I needed some help regarding a removal of a binary search tree. Yes its for a class, and yes I have tried working on it on my own, so no patronizing please. I have most of the code working, even the removal, I just don't know how to keep track of the parent, so that I can set its child to the child of the node to be removed. IE - if I had C / \ B D
15
5105
by: Foodbank | last post by:
Hi all, I'm trying to do a binary search and collect some stats from a text file in order to compare the processing times of this program (binary searching) versus an old program using linked lists. I'm totally new to binary searches by the way. Can anyone help me with the commented sections below? Much of the code such as functions and printfs has already been completed. Any help is greatly appreciated. Thanks,
1
2513
by: mathon | last post by:
hi, now i facing a problem which i do not know how to solve it...:( My binary search tree structures stores a double number in every node, whereby a higher number is appended as right child and a less or equal number is appended as a left child. Now i want to write a function which deletes the node with the highest number in the tree. I started the function as follows:
1
2954
by: hn.ft.pris | last post by:
I have the following code: Tree.h defines a simple binary search tree node structure ########## FILE Tree.h ################ #ifndef TREE_H #define TREE_H //using namespace std; template <typename Tclass Tree{ private: Tree<T*left;
6
16884
by: fdmfdmfdm | last post by:
This might not be the best place to post this topic, but I assume most of the experts in C shall know this. This is an interview question. My answer is: hash table gives you O(1) searching but according to your hash function you might take more memory than binary tree. On the contrary, binary tree gives you O(logN) searching but less memory. Am I right?
4
11016
by: whitehatmiracle | last post by:
Hello I have written a program for a binary tree. On compiling one has to first chose option 1 and then delete or search. Im having some trouble with the balancing function. It seems to be going into an infinite loop, i think im messing up with the pointers. Heres the code. //press 1, first, Do not press it a second time!!!
11
1191
by: Defected | last post by:
Hi, How i can create a Binary Search Tree with a class ? thanks
1
1314
by: sarajan82 | last post by:
Hi all, Given a binary search tree and a number n, how can we find the smallest node of the tree greater than n and the largest node smaller than n? For example for the following binary search tree where 5 is root and 4 is the left and 6 the right child, for an input of 5, 4 and 6 will be output: 5
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10578
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9152
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7620
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6853
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5522
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.